开发环境:
IDE:Myeclipse10.0
数据库:Oracle(SQL Developer)
Web容器:Tomcat 7.0
JDK:1.6
Struts:2.0
Hibernate:3.3
数据库:(ID为主键,设置了序列以及触发器SEQUENCE_ID,使得ID自增)
注意事项:
创建项目以后,为项目添加Sturts和Hibernate能力
连接数据库并生成POJO类:Hibernate框架连接SQL sever 2016完整详细步骤
还有一个一定会出错的地方,因为Hibernate和Struts 2 中有相同的包(版本不同)会引起冲突,所以要把Struts 2 中的antlr-2.7.2.jar移除,具体操作可以看这篇:java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I最终解决方案
编码步骤:
- 使用hibernate框架生成数据实体POJO类,即该项目中的Userinfo类
- 编写逻辑层UserDAO类
- 编写控制层Action类,分为登录Action和注册Action
- 编写视图层JSP,分为登录界面和注册页面,以及登录、注册成功后通通跳转到成功界面
- 编写struts.xml,分为两个action,因为有两张form表单要填写以对应跳转不同的视图
POJO类:Userinfo.java
package com.ov; /** * Userinfo entity. @author MyEclipse Persistence Tools */ public class Userinfo implements java.io.Serializable { // Fields private Integer id; private String username; private String password; private String repassword; // Constructors /** default constructor */ public Userinfo() { } /** full constructor */ public Userinfo(String username, String password, String repassword) { this.username = username; this.password = password; this.repassword = repassword; } // 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 getRepassword() { return this.repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } }
自动生成的Userinfo.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"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.ov.Userinfo" table="USERINFO" schema="SYSTEM"> <id name="id" type="java.lang.Integer"> <column name="ID" precision="9" scale="0" /> <generator class="sequence"> <param name="sequence">SEQUENCE_ID</param> </generator> </id> <property name="username" type="java.lang.String"> <column name="USERNAME" length="50" /> </property> <property name="password" type="java.lang.String"> <column name="PASSWORD" length="50" /> </property> <property name="repassword" type="java.lang.String"> <column name="REPASSWORD" length="50" /> </property> </class> </hibernate-mapping>
UserDAO.java
package com.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.ov.Userinfo; import com.util.HibernateSessionFactory; public class UserDAO { private Session session; private Transaction t; //获取session连接 public void getCurrentSession() { session = HibernateSessionFactory.getSession(); } //关闭session连接 public void closeSession() { if(session != null){ HibernateSessionFactory.closeSession(); } } /** * 登录:验证用户名和密码 * @param user * @return true 存在 * @return false 不存在 */ public boolean loginByUser(String username,String password){ getCurrentSession(); t = session.beginTransaction(); Query query = session.createQuery("from Userinfo where username='"+username+"' and password='"+password+"'"); List list = query.list(); closeSession(); if(list!=null && list.size()>0) { //存在用户名和密码 return true; } return false; } /** * 注册:先查询表中是否存在相同用户名,若无则增加,有则提示 * @param userinfo * @return true 成功 * @return false 失败 */ public boolean registByUser(Userinfo userinfo) { try{ getCurrentSession(); t = session.beginTransaction(); String username = userinfo.getUsername(); String password = userinfo.getPassword(); String repassword = userinfo.getRepassword(); Query query = session.createQuery("from Userinfo where username='"+username+"'"); //query.setString(0, username); List list = query.list(); if(list.size()>0){ //如果表中已经有相同的用户名 return false; } else{ session.save(userinfo); t.commit(); return true; } }catch (Exception e) { e.printStackTrace(); } finally{ closeSession(); } return false; } }
LoginAction.java
package com.action; import java.util.Map; import org.hibernate.Session; import com.dao.UserDAO; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.ov.Userinfo; public class LoginAction extends ActionSupport { private String username; private String password; private String msg;//用于显示错误信息 /** * 处理用户请求的execute方法 */ public String execute() throws Exception { //获得会话,用来保存当前登录用户的信息! Map<String,Object> session = ActionContext.getContext().getSession(); Userinfo userinfo = new Userinfo(); userinfo.setUsername(username); userinfo.setPassword(password); session.put("userinfo", userinfo); return SUCCESS; } public void validate() { if(username==null || username.equals("")){ this.addFieldError("username", "用户名不能为空!"); } else if(password==null || password.equals("")){ this.addFieldError("password", "密码不能为空!"); } else{ UserDAO dao = new UserDAO(); if(dao.loginByUser(username,password) == false){ this.addFieldError("username", "用户名或密码错误!"); } } } 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 String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
RegistAction.java
package com.action; import java.util.Map; import org.hibernate.Session; import com.dao.UserDAO; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.ov.Userinfo; public class LoginAction extends ActionSupport { private String username; private String password; private String msg;//用于显示错误信息 /** * 处理用户请求的execute方法 */ public String execute() throws Exception { //获得会话,用来保存当前登录用户的信息! Map<String,Object> session = ActionContext.getContext().getSession(); Userinfo userinfo = new Userinfo(); userinfo.setUsername(username); userinfo.setPassword(password); session.put("userinfo", userinfo); return SUCCESS; } public void validate() { if(username==null || username.equals("")){ this.addFieldError("username", "用户名不能为空!"); } else if(password==null || password.equals("")){ this.addFieldError("password", "密码不能为空!"); } else{ UserDAO dao = new UserDAO(); if(dao.loginByUser(username,password) == false){ this.addFieldError("username", "用户名或密码错误!"); } } } 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 String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
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="default" extends="struts-default"> <!-- 登录 --> <action name="loginAction" class="com.action.LoginAction"> <result name="success">/success.jsp</result> <result name="input">/index.jsp</result> </action> <!-- 注册 --> <action name="registAction" class="com.action.RegistAction"> <result name="success">/success.jsp</result> <result name="input">/register.jsp</result> </action> </package> </struts>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>主页</title> </head> <body> <s:form action="loginAction" method="post"> <s:fielderror><s:property value="msg"/></s:fielderror> <s:textfield label="用户名" name="username"/> <s:password label="密码" name="password"/> <s:a href="register.jsp">注册</s:a> <s:submit value="登录"/> </s:form> </body> </html>
register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>主页</title> </head> <body> <s:form action="registAction" method="post"> <s:fielderror><s:property value="msg"/></s:fielderror><br> <s:textfield label="用户名" name="username"/> <s:password label="密码" name="password"/> <s:password label="确认密码" name="repassword"/> <s:submit value="提交"/> <s:reset value="重置"/> </s:form> </body> </html>
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>主页</title> </head> <body> <s:set name="userinfo" value="#session['userinfo']"></s:set> <s:property value="#userinfo.username"/>,您好! </body> </html>