Struts2和hibernate框架整合实现简单的注册登陆功能

来源:互联网 发布:mysql variables 修改 编辑:程序博客网 时间:2024/05/17 22:56

Struts2和hibernate框架整合实现简单的注册登陆功能

项目结构:
这里写图片描述
LoginAction.java

package action;import vo.User;import vo.UserDAO;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport {    /**     *      */    private static final long serialVersionUID = 1L;    private User user;    public User getUser() {        return user;}    public void setUser(User user) {        this.user = user;}    public String execute()throws Exception{        if((user=new UserDAO().LoginCheck(user.getUsername(), user.getPassword(),user.getRole()))==null){            return ERROR;        }        if(user.getRole()=="1"){                return "admin";            }else{                return SUCCESS;}        }}

RegistAction.java

package action;import vo.User;import vo.UserDAO;import com.opensymphony.xwork2.ActionSupport;public class RegistAction extends ActionSupport {    /**     *      */    private static final long serialVersionUID = 1L;    private User user=null;    private String repassword;    public String getRepassword() {        return repassword;    }    public void setRepassword(String repassword) {        this.repassword = repassword;    }    //UserDAO userDao=new UserDAO();    @Override    public String execute() throws Exception {        User selectUser=new User();        if((selectUser=new UserDAO().selectRegist(user.getUsername()))==null){            User u=new User();            u.setUsername(user.getUsername());            u.setPassword(user.getPassword());            new UserDAO().saveRegist(u);            return "success";        }else{            return "error";        }    }    public User getUser() {        return user;    }    public void setUser(User user) {        this.user = user;    }}

LoginAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">    <validators>        <field name="user.username">            <field-validator type="requiredstring">            <param name="trim">true</param>            <message>用户名不能为空</message>            </field-validator>        </field>        <field name="user.password">        <field-validator type="regex">            <param name="expression"><![CDATA[(\w{4,8})]]></param>            <message>密码长度必须在4~8之间</message>            </field-validator>        </field>    </validators>

RegistAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">    <validators>        <field name="user.username">            <field-validator type="requiredstring">            <param name="trim">true</param>            <message>用户名不能为空</message>            </field-validator>        </field>        <field name="user.password">        <field-validator type="regex">            <param name="expression"><![CDATA[(\w{4,8})]]></param>            <message>密码长度必须在4~8之间</message>            </field-validator>        </field>        <field name="repassword">        <field-validator type="fieldexpression">            <param name="expression"><![CDATA[(repassword==user.password)]]></param>            <message>两次输入的密码要一致!</message>        </field-validator>        </field>    </validators>

HibernateSessionFactory.java

package util;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;/** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution.  Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */public class HibernateSessionFactory {    /**      * Location of hibernate.cfg.xml file.     * Location should be on the classpath as Hibernate uses       * #resourceAsStream style lookup for its configuration file.      * The default classpath location of the hibernate config file is      * in the default package. Use #setConfigFile() to update      * the location of the configuration file for the current session.        */    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();    private static org.hibernate.SessionFactory sessionFactory;    private static Configuration configuration = new Configuration();    private static ServiceRegistry serviceRegistry;     static {        try {            configuration.configure();            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();            sessionFactory = configuration.buildSessionFactory(serviceRegistry);        } catch (Exception e) {            System.err.println("%%%% Error Creating SessionFactory %%%%");            e.printStackTrace();        }    }    private HibernateSessionFactory() {    }    /**     * Returns the ThreadLocal Session instance.  Lazy initialize     * the <code>SessionFactory</code> if needed.     *     *  @return Session     *  @throws HibernateException     */    public static Session getSession() throws HibernateException {        Session session = (Session) threadLocal.get();        if (session == null || !session.isOpen()) {            if (sessionFactory == null) {                rebuildSessionFactory();            }            session = (sessionFactory != null) ? sessionFactory.openSession()                    : null;            threadLocal.set(session);        }        return session;    }    /**     *  Rebuild hibernate session factory     *     */    public static void rebuildSessionFactory() {        try {            configuration.configure();            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();            sessionFactory = configuration.buildSessionFactory(serviceRegistry);        } catch (Exception e) {            System.err.println("%%%% Error Creating SessionFactory %%%%");            e.printStackTrace();        }    }    /**     *  Close the single hibernate session instance.     *     *  @throws HibernateException     */    public static void closeSession() throws HibernateException {        Session session = (Session) threadLocal.get();        threadLocal.set(null);        if (session != null) {            session.close();        }    }    /**     *  return session factory     *     */    public static org.hibernate.SessionFactory getSessionFactory() {        return sessionFactory;    }    /**     *  return hibernate configuration     *     */    public static Configuration getConfiguration() {        return configuration;    }}

AbstractUser.java

package vo;/** * AbstractUser entity provides the base persistence definition of the User * entity. @author MyEclipse Persistence Tools */public abstract class AbstractUser implements java.io.Serializable {    // Fields    private Integer id;    private String username;    private String password;    private String role;    // Constructors    /** default constructor */    public AbstractUser() {    }    /** full constructor */    public AbstractUser(String username, String password,String role) {        this.username = username;        this.password = password;        this.role=role;    }    // Property accessors    public Integer getId() {        return this.id;    }    public void setId(Integer id) {        this.id = id;    }    public String getUsername() {        return this.username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return this.password;    }    public void setPassword(String password) {        this.password = password;    }    public String getRole() {        return role;    }    public void setRole(String role) {        this.role = role;    }}

BaseHibernateDAO.java

package vo;import org.hibernate.Session;import util.HibernateSessionFactory;/** * Data access object (DAO) for domain model * @author MyEclipse Persistence Tools */public class BaseHibernateDAO implements IBaseHibernateDAO {    public Session getSession() {        return HibernateSessionFactory.getSession();    }}

IBaseHibernateDAO.java

package vo;import org.hibernate.Session;/** * Data access interface for domain model * @author MyEclipse Persistence Tools */public interface IBaseHibernateDAO {    public Session getSession();}

User.java

package vo;/** * User entity. @author MyEclipse Persistence Tools */public class User extends AbstractUser implements java.io.Serializable {    // Constructors    /** default constructor */    public User() {    }    /** full constructor */    public User(String username, String password,String role) {        super(username, password,role);    }}

UserDAO.java

package vo;import java.util.Iterator;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import util.HibernateSessionFactory;/** * A data access object (DAO) providing persistence and search support for User * entities. Transaction control of the save(), update() and delete() operations * can directly support Spring container-managed transactions or they can be * augmented to handle user-managed Spring transactions. Each of these methods * provides additional information for how to configure it for the desired type * of transaction control. *  * @see vo.User * @author MyEclipse Persistence Tools */public class UserDAO extends BaseHibernateDAO {    private static final Logger log = LoggerFactory.getLogger(UserDAO.class);    // property constants    public static final String USERNAME = "username";    public static final String PASSWORD = "password";    /**     * @param username     * @return 检查用户名是否存在     */    public User selectRegist(String username){        try{        Session session=getSession();        Query query=session.createQuery("from User where username=?");        query.setParameter(1, username);        List list=query.list();        User user = null;         Iterator it=list.iterator();         while(it.hasNext()){             user=(User)it.next();             System.out.println(user.getUsername());         }            return user;        }catch(Exception e){            e.printStackTrace();            return null;        }    }    /**     * @param username     * @param password     * @return 登陆检查用户名和密码,确认身份     */    public User LoginCheck(String username,String password,String role){        System.out.println("this is LoginCheck method !");        log.debug("LoginChecking User instance");        try {                Session session = getSession();                /*Transaction tran = session.beginTransaction();*/                Query queryObject = session.createQuery("from User where username=? and password=? and role=?");                System.out.println("pass1");                queryObject.setString(0, username);                queryObject.setString(1,password);                queryObject.setString(2, role);                List list=queryObject.list();                /*tran.commit();*/                System.out.println("pass2");                User user = null;                 Iterator it=list.iterator();                 while(it.hasNext()){                     user=(User)it.next();                     //System.out.println(user.getUsername());                 }                return user;        } catch (RuntimeException re) {            log.error("find by property name failed", re);            throw re;        }           }    /**     * @param user     * 进行注册,向数据库插入数据     */    public void saveRegist(User user){        Session session = null ;        Transaction tx=null;        try{            session = getSession();            tx=session.beginTransaction();            session.save(user);            tx.commit();        }catch(Exception e){            e.printStackTrace();            System.out.println("提交数据出错了");            if(tx!=null)tx.rollback();        }finally{            session.close();        }    }}

User.hbm.xml

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><!--     Mapping file autogenerated by MyEclipse Persistence Tools--><hibernate-mapping>    <class name="vo.User" table="user" catalog="bookmanage">        <id name="id" type="java.lang.Integer">            <column name="Id" />            <generator class="identity" />        </id>        <property name="username" type="java.lang.String">            <column name="username" not-null="true" />        </property>        <property name="password" type="java.lang.String">            <column name="password" not-null="true" />        </property>        <property name="role" type="java.lang.String">            <column name="role" not-null="true" />        </property>    </class></hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools.                   --><hibernate-configuration>    <session-factory>        <property name="dialect">            org.hibernate.dialect.MySQLDialect        </property>        <property name="connection.url">            jdbc:mysql://localhost:3306/bookManage        </property>        <property name="connection.username">root</property>        <property name="connection.password">1011</property>        <property name="connection.driver_class">            com.mysql.jdbc.Driver        </property>        <property name="myeclipse.connection.profile">            bookDriver        </property>        <mapping resource="vo/User.hbm.xml" />    </session-factory></hibernate-configuration>

struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts><package name="mypackage" extends="struts-default" namespace="/"><action name="login" class="action.LoginAction">    <result name="success">/success.jsp</result>    <result name="error">/error.jsp</result>    <result name="admin">/admin.jsp</result>    <result name="input">/index.jsp</result></action><action name="regist" class="action.RegistAction">    <result name="success">/success.jsp</result>    <result name="error">/error.jsp</result>    <result name="input">/regist.jsp</result></action></package></struts>  

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@taglib prefix="s" uri="/struts-tags"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>login</title>  </head>  <body>    <s:form action="login" method="post">    <s:radio list="#{'1':'admin','0':'user' }" name="user.role" label="role" value="0" />    <s:textfield name="user.username" label="用户名"/>    <s:password name="user.password" label="密码"/>    <s:submit value="登陆"/>    <a name="regist" id="loginRegist" href="regist.jsp">regist</a>  </s:form>  </body></html>

regist.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@taglib prefix="s" uri="/struts-tags"%><html>  <head>    <title>regist</title>  </head>  <body>    <s:form action="regist">    <s:textfield name="user.username" label="用户名"/>    <s:password name="user.password" label="密码"/>    <s:password name="repassword" label="确认密码"/>    <s:submit value="注册"/>  </s:form>  </body></html>

需要注意的是引入myeclipse自带的struts2和hibernate时,antlr-2.7.7.jar包重复,运行时会报错,本例的用法是直接将struts2的类库导出去,将struts用到的几个jar包铐入工程,放置在/linda/WebRoot/WEB-INF/lib目录下。(如果没有不清楚如何配置struts和hibernate,可以看一下这篇博客:http://blog.csdn.net/weixin_36380516/article/details/53822344)

2 0