Myeclipse下的Struts 2 + Hibernate 的注册登录系统
2015-06-25 20:41
543 查看
文件目录结构如下:
数据库test的表info如下:
详细步骤如下:
1.新建一个web project,命名为ch14,然后右击ch14,选择倒数第二项 myeclipse,依次添加Struts2核心组件和Hibernate核心组件;然后把mysql的驱动文件包拷贝进/ch14/WebRoot/WEB-INF/lib 下
2.登录界面的jsp文件代码(login.jsp)
3.注册页面代码(register.jsp)
4.登录成功界面代码(success.jsp)
4.在src下新建4个包,分别为addHibernateFile、loginRegisterAction、loginRegisterDao、PO,其中addHibernateFile包是在导入Hibernate核心组件的时候建立的
5.addHibernateFile下的HibernateSessionFactory.java代码:
6.loginRegisterAction下的代码:
(1)LoginAction.java
(2)RegisterAction.java
7.loginRegisterDao下的代码,LoginRegisterInfo.java
8.PO下的代码:
(1)UserInfoPO.java
(2)UserInfoPO.hbm.xml
9.代码:hibernate.cfg.xml
10.代码:struts.xml
11.代码:web.xml
OK,全部代码贴完毕,接下来是运行流程:
首先进去的是注册页面:register.jsp,填写注册信息:用户名和密码,有一个validate验证,如下第一个图:
如果验证通过,就会跳转到登录界面,如上第二个图:
如果用户名和密码都正确,则登录成功,如上第三个图:
好了,上面是大概的流程,以下就是稍微详细一点的流程(本人菜鸟,正在学习中,大牛勿喷呀):
首先进入register.jsp,提交之后会向tomcat服务器发送请求,服务器接收到请求之后,会查看web.xml配置文件,发现所有请求都交给struts2这个过滤器来处理;struts.xml就会根据发来的请求,找到与请求相应的action,发现是register这个action,就会去执行loginRegisterAction包里面的RegisterAction.java类,先执行validate()这个验证方法,然后根据类里面的execute返回的信息执行下一步;如果信息是success,则表示成功了,跳转到login.jsp这个页面;如果是error或者input,则表示失败了,重新回到register.jsp页面;成功跳转到login.jsp之后,填写用户名密码,提交,又会发送请求到tomcat服务器,紧接着服务器会查看web.xml文件,发现被拦截到了struts.xml中,继续查找struts.xml中的action,发现login这个action与之匹配,执行loginRegisterAction包里面的LoginAction.java类,先执行validate()这个验证方法,再执行execute()方法,根据返回的信息,如果成功success则跳转到success.jsp页面,登录成功,如果失败error则返回登录界面login.jsp
数据库test的表info如下:
详细步骤如下:
1.新建一个web project,命名为ch14,然后右击ch14,选择倒数第二项 myeclipse,依次添加Struts2核心组件和Hibernate核心组件;然后把mysql的驱动文件包拷贝进/ch14/WebRoot/WEB-INF/lib 下
2.登录界面的jsp文件代码(login.jsp)
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <base href="<%=basePath%>"> <title><s:text name="基于SH的登录和注册系统"></s:text></title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body bgcolor="#CCCCFF"> <s:form action="login" method="post"> <br><br><br><br><br><br> <table border="1" align="center" bgcolor="#AABBCCDD"> <tr><td><s:textfield name="userName" label="用户名字" size="16"/></td></tr> <tr><td><s:password name="password" label="用户密码" size="18"/></td></tr> <tr><td colspan="2" align="center"><s:submit value="登录"/></td></tr> <tr><td colspan="2" align="center"><s:a href="http://localhost:8080/ch14/register.jsp">注册</s:a></td></tr> </table> </s:form> </body> </html>
3.注册页面代码(register.jsp)
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <base href="<%=basePath%>"> <title><s:text name="基于SH的登录和注册系统"></s:text></title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body bgcolor="#CCCCFF"> <s:form action="register" method="post"> <br><br><br><br><br><br> <table border="1" align="center" bgcolor="#AABBCCDD"> <tr><td><s:textfield name="userName" label="用户名字" size="16"/></td></tr> <tr><td><s:password name="password1" label="用户密码" size="18" /></td></tr> <tr><td><s:password name="password2" label="再次输入密码" size="18" /></td></tr> <tr><td colspan="2" align="center"> <input type="submit" value="提交"/> <input type="reset" value="清空"/> </td> </tr> <tr><td colspan="2" align="center"> <s:a href="http://localhost:8080/ch14/login.jsp">登录</s:a></td></tr> </s:form> </table> </body> </html>
4.登录成功界面代码(success.jsp)
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <base href="<%=basePath%>"> <title><s:text name="基于SH的登录和注册系统"></s:text></title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body bgcolor="#CCCCFF"> <hr> <table border="0" align="center" bgcolor="#AABBCCDD"> <tr><td>欢迎${userName },登录成功!</td></tr> </table> </body> </html>
4.在src下新建4个包,分别为addHibernateFile、loginRegisterAction、loginRegisterDao、PO,其中addHibernateFile包是在导入Hibernate核心组件的时候建立的
5.addHibernateFile下的HibernateSessionFactory.java代码:
package addHibernateFile; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; 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(); } } public HibernateSessionFactory() { } public SessionFactory config(){ try{ Configuration configuration = new Configuration(); Configuration configure = configuration.configure("hibewnate.cfg.xml"); return configure.buildSessionFactory(); }catch(Exception e){ e.getMessage(); return null; } } /** * 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; } }
6.loginRegisterAction下的代码:
(1)LoginAction.java
package loginRegisterAction; import java.util.List; import loginRegisterDao.*; import PO.UserInfoPO; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private String userName; private String password; private String message="error"; private List list; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void validate(){ if(this.getUserName()==null || this.getUserName().length()==0){ addFieldError("userName", "用户名不能为空!"); }else{ LoginRegisterInfo info = new LoginRegisterInfo(); list = info.queryInfo("userName",this.getUserName()); if(list.size()==0){ addFieldError("userName", "该用户尚未注册!"); }else{ UserInfoPO ui = new UserInfoPO(); int count = 0; for(int i=0; i<list.size(); i++){ count++; ui = (UserInfoPO)list.get(i); if(this.getUserName().equals(ui.getUserName())){ if(ui.getPassword().equals(this.getPassword())){ message = SUCCESS; }else{ addFieldError("password", "登录密码不正确!"); } } } } } } public String execute(){ return message; } }
(2)RegisterAction.java
package loginRegisterAction; import java.util.List; import loginRegisterDao.LoginRegisterInfo; import PO.UserInfoPO; import com.opensymphony.xwork2.ActionSupport; public class RegisterAction extends ActionSupport { private String userName; private String password1; private String password2; private String mess=ERROR; private List list; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword1() { return password1; } public void setPassword1(String password1) { this.password1 = password1; } public String getPassword2() { return password2; } public void setPassword2(String password2) { this.password2 = password2; } public void validate(){ if(this.getUserName()==null || this.getUserName().length()==0){ addFieldError("userName", "用户名不能为空!"); }else{ LoginRegisterInfo info = new LoginRegisterInfo(); list = info.queryInfo("userName",this.getUserName()); UserInfoPO ui = new UserInfoPO(); for(int i=0; i<list.size(); i++){ ui = (UserInfoPO)list.get(i); if(ui.getUserName().equals(this.getUserName())){ addFieldError("userName", "用户名已存在!"); } } } if(this.getPassword1()==null || this.getPassword1().length()==0){ addFieldError("password1", "登录密码不允许为空!"); }else if(this.getPassword2()==null || this.getPassword2().length()==0){ addFieldError("password2", "重复密码不允许为空!"); }else if(!this.getPassword1().equals(this.getPassword2())){ addFieldError("password2", "两次密码不一致"); } } public UserInfoPO userInfo(){ UserInfoPO info = new UserInfoPO(); info.setUserName(this.getUserName()); info.setPassword(this.getPassword1()); return info; } public String execute() throws Exception{ LoginRegisterInfo lr = new LoginRegisterInfo(); String ri = lr.saveInfo(userInfo()); if(ri.equals("success")){ mess = SUCCESS; } return mess; } }
7.loginRegisterDao下的代码,LoginRegisterInfo.java
package loginRegisterDao; import java.util.List; import javax.swing.JOptionPane; import PO.UserInfoPO; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import addHibernateFile.HibernateSessionFactory; public class LoginRegisterInfo { private Session session; private Transaction transaction; private Query query; HibernateSessionFactory getSession; public LoginRegisterInfo() { } public String saveInfo(UserInfoPO info) { String mess = "error"; getSession = new HibernateSessionFactory(); session = getSession.getSession(); try { transaction = session.beginTransaction(); session.save(info); transaction.commit(); mess = "success"; return mess; } catch (Exception e) { message("RegisterInfo.error:" + e); e.printStackTrace(); return null; } } public List queryInfo(String type, Object value) { getSession = new HibernateSessionFactory(); session = getSession.getSession(); transaction = session.beginTransaction(); / try { String hqlsql = "from UserInfoPO as u where u.userName='" + value + "'"; query = session.createQuery(hqlsql); // query.setParameter(0, value); List list = query.list(); transaction.commit(); return list; } catch (Exception e) { message("LoginRegisterInfo类中有异常,异常为:" + e); e.printStackTrace(); return null; } } public void message(String mess) { int type = JOptionPane.YES_NO_OPTION; String title = "提示信息"; JOptionPane.showMessageDialog(null, mess, title, type); } }
8.PO下的代码:
(1)UserInfoPO.java
package PO; public class UserInfoPO { private int id; private String userName; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
(2)UserInfoPO.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class catalog="test" name="PO.UserInfoPO" table="info"> <id name="userName" type="string"> <column length="30" name="userName"/> <generator class="assigned"/> </id> <property generated="never" lazy="false" name="id" type="int"> <column length="10" name="id" not-null="true"/> </property> <property generated="never" lazy="false" name="password" type="string"> <column length="30" name="password" not-null="true"/> </property> </class> </hibernate-mapping>
9.代码: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="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">1234</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <mapping resource="PO/UserInfoPO.hbm.xml"/> </session-factory> </hibernate-configuration>
10.代码: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> <!-- <include file="example.xml"/> --> <package name="default" extends="struts-default"> <action name="register" class="loginRegisterAction.RegisterAction"> <result name="success">/login.jsp</result> <result name="input">/register.jsp</result> <result name="error">/register.jsp</result> </action> <action name="login" class="loginRegisterAction.LoginAction"> <result name="success">/success.jsp</result> <result name="input">/login.jsp</result> <result name="error">/login.jsp</result> </action> </package> </struts>
11.代码:web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
OK,全部代码贴完毕,接下来是运行流程:
首先进去的是注册页面:register.jsp,填写注册信息:用户名和密码,有一个validate验证,如下第一个图:
如果验证通过,就会跳转到登录界面,如上第二个图:
如果用户名和密码都正确,则登录成功,如上第三个图:
好了,上面是大概的流程,以下就是稍微详细一点的流程(本人菜鸟,正在学习中,大牛勿喷呀):
首先进入register.jsp,提交之后会向tomcat服务器发送请求,服务器接收到请求之后,会查看web.xml配置文件,发现所有请求都交给struts2这个过滤器来处理;struts.xml就会根据发来的请求,找到与请求相应的action,发现是register这个action,就会去执行loginRegisterAction包里面的RegisterAction.java类,先执行validate()这个验证方法,然后根据类里面的execute返回的信息执行下一步;如果信息是success,则表示成功了,跳转到login.jsp这个页面;如果是error或者input,则表示失败了,重新回到register.jsp页面;成功跳转到login.jsp之后,填写用户名密码,提交,又会发送请求到tomcat服务器,紧接着服务器会查看web.xml文件,发现被拦截到了struts.xml中,继续查找struts.xml中的action,发现login这个action与之匹配,执行loginRegisterAction包里面的LoginAction.java类,先执行validate()这个验证方法,再执行execute()方法,根据返回的信息,如果成功success则跳转到success.jsp页面,登录成功,如果失败error则返回登录界面login.jsp
相关文章推荐
- Struts2 奇怪的老是调用index方法
- Java I/O 详解
- Java 中的成员内部类(转载)
- Java命名规范
- SpringMVC将数据返回到页面
- JDK自带VM分析工具jps|jstat|jmap|jconsole使用
- Java设计模式
- java选择排序法
- 自娱自乐--爬虫java实践
- 贝叶斯分类(java)
- struts2 ActionSupport关联源码
- java.util.properties使用方法
- Spring IO 平台介绍
- spring源码理解-BeanFactory子类XmlBeanFactory的创建过程
- java byte 与 int float转换
- java对象与json对象间的相互转换
- 批量下载的实现及java.lang.IllegalStateException异常 推荐
- JAVA实现远程录屏或广播屏幕
- Java 强引用、软引用、弱引用、虚引用
- Eclipse反逆向工程hibernate tool的安装与使用~~