您好,登錄后才能下訂單哦!
本文實例為大家分享了struts2和hibernate實現登錄和注冊功能,供大家參考,具體內容如下
1、該項目使用MySQL數據庫,數據庫名為test,表名info,如圖所示:
2、配置web.xml(Struts2使用)
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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_2_5.xsd"> <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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
3、編寫視圖組件(JSP頁面)
(1)登錄頁面login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><s:text name="基于SH的登錄注冊系統" /></title> </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/hibernate01/register.jsp">注冊</s:a> </td> </tr> </table> </s:form> </body> </html>
(2)登陸成功頁面success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body bgcolor="#CCCCFF"> <hr> <table> <tr> <td> 歡迎<s:property value="userName"/>,登陸成功! </td> </tr> </table> <hr> </body> </html>
(3)注冊頁面register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </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/hibernate01/login.jsp">返回</s:a> </td> </tr> </table> </s:form> </body> </html>
4、業務控制器Action
(1)登錄頁面對應的業務控制器LoginAction.java
其中,重寫valiadate()方法,進行手工驗證
package loginRegisterAction; import java.util.List; import loginRegisterDao.LoginRegisterInfo; 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(); for(int i=0;i<list.size();i++){ 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() throws Exception{ 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; //ERROR等同于"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; } }
5、在struts.xml中配置Action
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <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>
6、Hibernate的配置文件
使用Hibernate需要通過Hibernate的配置文件加載數據庫驅動以及與數據建立連接,配置文件為hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8</property> <property name="connection.username">root</property> <property name="connection.password"></property> <!-- 指定數據庫的方言 --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 加入映射文件 --> <mapping resource="PO/UserInfoPO.hbm.xml"/> </session-factory> </hibernate-configuration>
7、加載上面Hibernate配置文件的類(HIbernateSessionFactory.java)
package addHibernateFile; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory { private SessionFactory sessionFactory; public HibernateSessionFactory(){ } public SessionFactory config(){ try{ Configuration configuration= new Configuration(); Configuration configure=configuration.configure("hibernate.cfg.xml"); return configure.buildSessionFactory(); }catch(Exception e){ e.getMessage(); return null; } } public Session getSession(){ sessionFactory=config(); return sessionFactory.openSession(); } }
8、PO對象以及對應的映射文件(在同一個包下)
(1)PO對象的類UserInfoPO.Java
package PO; /* * 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) PO對應的映射文件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> <!-- 配置PO對象與數據庫中表的對應關系使用class元素,name配置PO對象對應的類, table配置該PO對象在數據庫中對應的表名,catalog配置表對應的數據庫名 --> <class name="PO.UserInfoPO" table="info" catalog="test"> <!-- id元素配置PO對象與數據庫中表的對應id字段,name配置PO對象對應的屬性,type指定類型 generator元素將主鍵自動加入序列 --> <id name="id" type="int"> <column name="id"/> <generator class="assigned" /> </id> <property name="userName" type="string"> <column name="userName" length="30" not-null="true" /> </property> <property name="password" type="string"> <column name="password" length="30" not-null="true" /> </property> </class> </hibernate-mapping>
9、完成登錄和注冊業務功能
將登錄和注冊業務功能封裝到類LoginRegisterInfo(JavaBean)中
數據庫操作類LoginRegisterInfo.java:
package loginRegisterDao; /* * 登錄和注冊業務功能,封裝到這個JavaBean */ import java.util.List; import javax.swing.JOptionPane; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import PO.UserInfoPO; 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(); try{ String hqlsql="from UserInfoPO as u where u.userName=?"; query=session.createQuery(hqlsql); query.setParameter(0, value); List list=query.list(); transaction=session.beginTransaction(); 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); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。