User registration and login based on struts 2

Keywords: JSP Database Struts Java

After these days of learning, I have learned some basic knowledge about Struts. Here, I use Struts 2 to realize user registration and login, which helps us to better understand some working mechanisms of Struts.

First of all, import the necessary jar package of Struts2 and add configuration information in the web.xml configuration file (the basic settings of the Structs2 development environment, as mentioned in my last article, here is the link: Environment construction of struts 2)

Then, the design of the database, database name: Struts2 table: user

create table user(
Id int(11) primary key auto_increment,//record number
username varchar(10) not null,//Login account
userpassword varchar(10) not null,//Login password
userrealname varchar(50));//User's real name

insert into user values('0','TT','123','Howard');//Add data

Next, I will give you the code for the compilation of related classes:

(1) Describes the implementation of the user information class EndUser:

package com.user;

public class EndUser {
	private Integer Id;//Account number
	private String username;//Login account
	private String userpassword;//Login password
	private String userrealname;//User's real name
	
	
	public Integer getId() {
		return Id;
	}
	public void setId(Integer id) {
		Id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getUserpassword() {
		return userpassword;
	}
	public void setUserpassword(String userpassword) {
		this.userpassword = userpassword;
	}
	public String getUserrealname() {
		return userrealname;
	}
	public void setUserrealname(String userrealname) {
		this.userrealname = userrealname;
	}
	
	

}

(2) Write DBConnection class of database connection

package com.db_util;

import java.sql.*;

public class DBConnection {
	private static String driverName = "com.mysql.jdbc.Driver";//mysql database driver
	private static String userName = "root";//Database user name
	private static String userPwd = "hugh";//Database password
	private static String dbName = "struts2";//Database name
	
	public static Connection getDBConnection() {
		//How to get database connection object
		String url1 = "jdbc:mysql://localhost:3306/"+dbName;
		String url2 = "?user="+userName+"&password="+userPwd;
		String url3 = "&useUnicode=true&characterEncoding=utf-8";
		String url = url1+url2+url3; //Form database connection word
		Connection con = null;
		try {
			Class.forName(driverName);
			con = DriverManager.getConnection(url);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return con;
	}
	
	//Close resource objects of database connection
	public static void closeDB(Connection con,PreparedStatement pstm,ResultSet rs) {
		if(rs != null) try{
			rs.close();
		}catch(SQLException e) {
			e.printStackTrace();
		}
		if(pstm != null) try {
			pstm.close();
		}catch(SQLException e) {
			e.printStackTrace();
		}
		if(con != null) try{
		     con.close();
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}

}

(3) Implementation of DAO class UserDao class for database operation

package com.dao.user;
import java.sql.*;

import com.db_util.DBConnection;
import com.model.user.EndUser;

public class UserDao {
	public int save(EndUser user) {
		//How to insert a user into the database
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		con = DBConnection.getDBConnection();
		int row = 0;
		String sql = "insert into user(userName,userPassword,userRealName) values(?,?,?)";
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getUserName());
			pstmt.setString(2, user.getUserPassword());
			pstmt.setString(3, user.getUserRealName());
			row = pstmt.executeUpdate();
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			DBConnection.closeDB(con, pstmt, rs);
		}
		return row;
	}
	
	public EndUser find(EndUser user) {
		//Find a user from the database to verify registration
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		con = DBConnection.getDBConnection();
		EndUser user2 = null;
		String sql = "select * from user where userName=? and userPassword=?";
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getUserName());
			pstmt.setString(2, user.getUserPassword());
			rs = pstmt.executeQuery();
			if (rs.next()) {
				user2 = new EndUser();
				user2.setUserId(rs.getInt("id"));
				user2.setUserName(rs.getString("userName"));
				user2.setUserPassword(rs.getString("userPassword"));
				user2.setUserRealName(rs.getString("userRealName"));
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			DBConnection.closeDB(con, pstmt, rs);
		}
		return user2;
	}

}

(4) Design control class (Action class): UserAction.java

package com.action.user;

import com.dao.user.UserDao;
import com.model.user.EndUser;

public class UserAction {
	private EndUser user;
	private UserDao userDao = new UserDao();
	public String userLogin() throws Exception {
		//User login Action method
		String forward = null;
		EndUser user2 = userDao.find(user);
		if(user2 != null) {
			forward = "success";
		}else {
			forward = "failure";
		}
		return forward;
	}
	
	public String userRegister() throws Exception {
		//User registration Action method
		String forward = "error";//Error marking value when database saves data
		int flag = 0;
		EndUser user2 = (userDao.find(user));
		if(user2 != null) {
			forward = "erroe_user";//User name is already in use tag value
		}else {
			flag = userDao.save(user);
			if(flag == 1) {
				forward = "success";//Tag value registered successfully
			}
		}
		return forward;
	}

	public EndUser getUser() {
		return user;
	}

	public void setUser(EndUser user) {
		this.user = user;
	}

}

(5) Configuration file in Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <package name="user" namespace="/" extends="struts-default">
    
     <action name="register" class="com.action.user.UserAction" method="userRegister">
       <result name="success">/success.jsp</result>
       <result name="error">/failure.jsp</result>
       <result name="error_user">/failure_user.jsp</result>
     </action>
     <action name="logincheck" class="com.action.user.UserAction" method="userLogin">
          <result name="success">/login_success.jsp</result>
        <result name="failure">/login_failure.jsp</result>
     </action>
     
    </package>

</struts>

(6) Write JSP page

Main page (index.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>System home page</title>
</head>
<body>
//Welcome to our system!!!
</body>
</html>

Login page (login.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>Login page</title>
</head>
<body>
 <form action="/marketplace/logincheck" method="post">
 <table>
   <tr><th colspan="2">User login:</th></tr>
   <tr><td align="right">User name:</td><td><input name="user.username"/></td></tr>
   <tr><td align="right">Password:</td>
       <td><input type="password" name="user.userpassword"/></td></tr>
   <tr><td align="left"><input type="submit" value="Sign in"/></td>
       <td>Unregistered person, please register first, click<a href="/marketplace/register.jsp">register</a></td>
       </tr>
 </table>
 </form>
</body>
</html>

 

Login success page (login · success. JSP)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>Login successfully</title>
</head>
<body>
  Welcome, ${user.userrealname },You login successfully!<br>
  Enter the main page, please click<a href="/marketplace/index.jsp">Main page</a>
</body>
</html>

 

Login failure page (login? Failure. JSP)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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-81">
<title>Login failed</title>
</head>
<body>
 <h2 align="center">
   <font color="red">
    Sorry, your account number and password are incorrect!please
   </font>
   <a href="/marketplace/login.jsp">Re login</a>
 </h2>
</body>
</html>

 

Registration page (register.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>Registration page</title>
<script type="text/javascript">
  function isValidate(form) {
	  var username=document.getElementById("username").value;
	  var userpass=document.getElementById("userpassword").value;
	  var userpass1=document.getElementById("userpass1").value;
	  if(userpass != userpass1){
		  alert("The two passwords are not the same, please re-enter!");
		  return false;
	  }else if(userpass.length<=0 || username.length<=0) {
		  alert("User name and password cannot be empty, please re-enter!");
		  return false;
	  }else{
		  return true;
	  }
  }
</script>
</head>
<body>
 <h3 align="left">Welcome to register our system, please fill in your information carefully</h3>
 <form action="/marketplace/register" name="register" method="post" onsubmit="return isValidate()">
  <table>
    <tr><td align="right">Account name:</td>
        <td><input name="user.username" id="username"></td></tr>
    <tr><td align="right">Set password for your account:</td>
        <td><input type="password" name="user.userpassword" id="userpassword"></td></tr>
    <tr><td align="right">Reconfirm your password:</td>
        <td><input type="password" name="userpass1" id="userpass1"></td></tr>
    <tr><td align="right">Real name:</td>
        <td><input name="user.userrealname" id="userrealname"></td></tr>
    <tr><td align="right"><input type="submit" value="Submission"></td>
        <td colspan="2"><input type="reset" value="Rewrite"></td></tr>
   </table>
 </form>
</body>
</html>

 

Registration success page (success.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>Registration success page</title>
</head>
<body>
 Congratulations, ${user.userrealname },You have successfully registered our management system!<br>
 click<a href="/marketplace/login.jsp">Sign in</a>
</body>
</html>

 

Registration failure page (failure.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>Registration failure page</title>
</head>
<body>
//Sorry, you failed to register! Click here to re register</a>
</body>
</html>

 

Registration failure page 2 (failure? User. JSP)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>Registration failure page</title>
</head>
<body>
//Sorry, the user you registered already exists. Click here to re register</a>
</body>
</html>

Finally, it can be published in Tomcat.

Posted by doobster on Fri, 31 Jan 2020 14:27:40 -0800