服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 基于struts2和hibernate实现登录和注册功能

基于struts2和hibernate实现登录和注册功能

2021-01-27 11:17王晓东1号 Java教程

这篇文章主要为大家详细介绍了基于struts2和hibernate实现登录和注册功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了struts2hibernate实现登录注册功能,供大家参考,具体内容如下

1、该项目使用MySQL数据库,数据库名为test,表名info,如图所示:

基于struts2和hibernate实现登录和注册功能

 2、配置web.xml(Struts2使用) 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<%@ 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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ 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

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<%@ 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="提交" />&nbsp;&nbsp;
          <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()方法,进行手工验证

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!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 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!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&amp;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)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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:

  1. package loginRegisterDao; 
  2. /* 
  3.  * 登录和注册业务功能,封装到这个JavaBean 
  4.  */ 
  5. import java.util.List; 
  6.  
  7. import javax.swing.JOptionPane; 
  8.  
  9. import org.hibernate.Query; 
  10. import org.hibernate.Session; 
  11. import org.hibernate.Transaction; 
  12.  
  13. import PO.UserInfoPO; 
  14. import addHibernateFile.HibernateSessionFactory; 
  15.  
  16. public class LoginRegisterInfo { 
  17.  
  18.   private Session session; 
  19.   private Transaction transaction; 
  20.   private Query query; 
  21.   HibernateSessionFactory getSession; 
  22.    
  23.   public LoginRegisterInfo(){ 
  24.   } 
  25.    
  26.   public String saveInfo(UserInfoPO info){ 
  27.     String mess="error"
  28.     getSession=new HibernateSessionFactory(); 
  29.     session=getSession.getSession(); 
  30.     try
  31.       transaction=session.beginTransaction(); 
  32.       session.save(info); 
  33.       transaction.commit(); 
  34.       mess="success"
  35.       return mess; 
  36.     }catch(Exception e){ 
  37.       message("RegisterInfo.error:"+e); 
  38.       e.printStackTrace(); 
  39.       return null
  40.     } 
  41.   } 
  42.    
  43.   public List queryInfo(String type,Object value){ 
  44.     getSession=new HibernateSessionFactory(); 
  45.     session=getSession.getSession(); 
  46.     try
  47.       String hqlsql="from UserInfoPO as u where u.userName=?"
  48.       query=session.createQuery(hqlsql); 
  49.       query.setParameter(0, value); 
  50.       List list=query.list(); 
  51.       transaction=session.beginTransaction(); 
  52.       transaction.commit(); 
  53.       return list; 
  54.     }catch(Exception e){ 
  55.       message("LoginRegisterInfo类中有异常,异常为::"+e); 
  56.       e.printStackTrace(); 
  57.       return null
  58.       } 
  59.   } 
  60.    
  61.    
  62.   public void message(String mess){ 
  63.     int type=JOptionPane.YES_NO_OPTION; 
  64.     String title="提示信息"
  65.     JOptionPane.showMessageDialog(null, mess,title,type); 
  66.   } 
  67.    

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/Donnnnnn/p/5692182.html

延伸 · 阅读

精彩推荐