基于struts2和hibernate實(shí)現(xiàn)登錄和注冊功能
本文實(shí)例為大家分享了struts2和hibernate實(shí)現(xiàn)登錄和注冊功能,供大家參考,具體內(nèi)容如下
1、該項(xiàng)目使用MySQL數(shù)據(jù)庫,數(shù)據(jù)庫名為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的登錄注冊系統(tǒng)" /></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、業(yè)務(wù)控制器Action
(1)登錄頁面對應(yīng)的業(yè)務(wù)控制器LoginAction.java
其中,重寫valiadate()方法,進(jìn)行手工驗(yàn)證
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)注冊頁面對應(yīng)的業(yè)務(wù)控制器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", "重復(fù)密碼不許為空!"); }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的配置文件加載數(shù)據(jù)庫驅(qū)動(dòng)以及與數(shù)據(jù)建立連接,配置文件為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> <!-- 指定數(shù)據(jù)庫的方言 --> <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對象以及對應(yīng)的映射文件(在同一個(gè)包下)
(1)PO對象的類UserInfoPO.Java
package PO; /* * PO對象(持久化對象)的類,與數(shù)據(jù)庫相對應(yīng) */ 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對應(yīng)的映射文件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對象與數(shù)據(jù)庫中表的對應(yīng)關(guān)系使用class元素,name配置PO對象對應(yīng)的類, table配置該P(yáng)O對象在數(shù)據(jù)庫中對應(yīng)的表名,catalog配置表對應(yīng)的數(shù)據(jù)庫名 --> <class name="PO.UserInfoPO" table="info" catalog="test"> <!-- id元素配置PO對象與數(shù)據(jù)庫中表的對應(yīng)id字段,name配置PO對象對應(yīng)的屬性,type指定類型 generator元素將主鍵自動(dòng)加入序列 --> <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、完成登錄和注冊業(yè)務(wù)功能
將登錄和注冊業(yè)務(wù)功能封裝到類LoginRegisterInfo(JavaBean)中
數(shù)據(jù)庫操作類LoginRegisterInfo.java:
package loginRegisterDao; /* * 登錄和注冊業(yè)務(wù)功能,封裝到這個(gè)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); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringMVC轉(zhuǎn)發(fā)與重定向參數(shù)傳遞的實(shí)現(xiàn)詳解
這篇文章主要介紹了SpringMVC轉(zhuǎn)發(fā)與重定向參數(shù)傳遞,對于重定向,可以通過FlashMap或RedirectAttributes來在請求間傳遞數(shù)據(jù),因?yàn)橹囟ㄏ蛏婕皟蓚€(gè)獨(dú)立的HTTP請求,而轉(zhuǎn)發(fā)則在同一請求內(nèi)進(jìn)行,數(shù)據(jù)可以直接通過HttpServletRequest共享,需要的朋友可以參考下2022-07-07Java11?中基于嵌套關(guān)系的訪問控制優(yōu)化問題
在?Java?語言中,類和接口可以相互嵌套,這種組合之間可以不受限制的彼此訪問,包括訪問彼此的構(gòu)造函數(shù)、字段、方法,接下來通過本文給大家介紹Java11中基于嵌套關(guān)系的訪問控制優(yōu)化問題,感興趣的朋友一起看看吧2022-01-01Mac使用Idea配置傳統(tǒng)SSM項(xiàng)目(非maven項(xiàng)目)
本文主要介紹了Mac使用Idea配置傳統(tǒng)SSM項(xiàng)目(非maven項(xiàng)目),將展示如何設(shè)置項(xiàng)目結(jié)構(gòu)、添加依賴關(guān)系等,具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01Spring @ExceptionHandler注解統(tǒng)一異常處理和獲取方法名
這篇文章主要介紹了Spring注解之@ExceptionHandler 統(tǒng)一異常處理和獲取方法名,在實(shí)際項(xiàng)目中,合理使用@ExceptionHandler能夠提高代碼的可維護(hù)性和用戶體驗(yàn),通過本文的解析和實(shí)踐,讀者可以更好地理解和掌握@ExceptionHandler的用法和原理2023-09-09關(guān)于Nacos和Eureka的區(qū)別及說明
這篇文章主要介紹了關(guān)于Nacos和Eureka的區(qū)別及說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06使用Spring?Boot如何限制在一分鐘內(nèi)某個(gè)IP只能訪問10次
有些時(shí)候,為了防止我們上線的網(wǎng)站被攻擊,或者被刷取流量,我們會(huì)對某一個(gè)ip進(jìn)行限制處理,這篇文章,我們將通過Spring?Boot編寫一個(gè)小案例,來實(shí)現(xiàn)在一分鐘內(nèi)同一個(gè)IP只能訪問10次,感興趣的朋友一起看看吧2023-10-10關(guān)于JAVA_HOME路徑修改之后JDK的版本依然不更改的解決辦法
今天小編就為大家分享一篇關(guān)于JAVA_HOME路徑修改之后JDK的版本依然不更改的解決辦法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-04-04