一只倔强的笨猪

【JAVAEE】Strust2案例2-实现用户注册与登陆

1.模型组件的创建
实现数据库连接和关闭的工具类。
com.db_util/DBConnection.java

package com.db_util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DBConnection {
	private static String driverName="com.mysql.jdbc.Driver";
	private static String userName="root";
	private static String userPwd="123456";
	private static String dbName="user";
	public static Connection getDBConnection(){
		String url1="jdbc:mysql://localhost/"+dbName;
		String url2="?user="+userName+"&password="+userPwd;
		String url3="&useUnicode=true&characterEncoding=utf-8";
		String url=url1+url2+url3;
		Connection con=null;
		try {
			Class.forName(driverName);
			con=DriverManager.getConnection(url);
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return con;		
	}
	
	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();
			}		
	}
}

实现数据库操作的DAO业务类。
com.dao.user/UserDao.java

package com.dao.user;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

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

public class UserDao {
	// 想数据库中插入一个用户
		public int save(EndUser user) {
			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 int delete(EndUser user) {
			Connection con = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			int row = 0;
			con = DBConnection.getDBConnection();
			String sql = "delete from user where username=? ";
			try {
				pstmt = con.prepareStatement(sql);
				pstmt.setString(1, user.getUserName());
				row = pstmt.executeUpdate();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				DBConnection.closeDB(con, pstmt, rs);
			}
			return row;
		}

		// 修改用户值
		public int update(EndUser user, String newPassword) {
			Connection con = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			int row = 0;
			con = DBConnection.getDBConnection();
			String sql = "update from user set userpassword=? where username=? and userpassword=? ";
			try {
				pstmt = con.prepareStatement(sql);
				pstmt.setString(1, newPassword);
				pstmt.setString(2, user.getUserName());
				pstmt.setString(3, user.getUserPassword());
				row = pstmt.executeUpdate();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				DBConnection.closeDB(con, pstmt, rs);
			}
			return row;
		}

		// 从数据库中查找一个用户
		public EndUser find(EndUser user) {
			Connection con = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			con = DBConnection.getDBConnection();
			EndUser user2 = null;
			String sql = "select id,username,userpassword,userrealname 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;
		}

		// 列出所有用户
		public List<EndUser> findAll() {
			Connection con = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			List<EndUser> users = new ArrayList<EndUser>();
			con = DBConnection.getDBConnection();
			String sql = "select id,userName,userPassword,userRealName from user ";
			try {
				pstmt = con.prepareStatement(sql);
				rs = pstmt.executeQuery();
				while (rs.next()) {
					EndUser user = new EndUser();
					user.setUserId(rs.getInt("id"));
					user.setUserName(rs.getString("username"));
					user.setUserPassword(rs.getString("userpassword"));
					user.setUserRealName("userRealName");
					users.add(user);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				DBConnection.closeDB(con, pstmt, rs);
			}
			return users;
		}
}

用户JavaBean类,用户描述用户信息及相关的处理方法。
com.model.user/EndUser.java

package com.model.user;

public class EndUser {
	private Integer userId;
	private String userName;
	private String userPassword;
	private String userRealName;
	
	public EndUser() {}
	
	public EndUser(Integer userId, String userName, String userPassword,String userRealName) {		
		this.userId = userId;
		this.userName = userName;
		this.userPassword = userPassword;
		this.userRealName = userRealName;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	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.创建Action类包含用户登陆和注册方法。
com.action.user/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();

	// 用户登录Action方法
	public String userLogin() throws Exception {
		String forward = null;
		EndUser user2 = userDao.find(user);
		if (user2 != null) {
			forward = "success"; //登录成功标记值
			user.setUserRealName(user2.getUserRealName());
		} else {
			forward = "failure";//登录失败标记值
		}
		return forward;
	}

	// 用户注册Action方法
	public String userRegister() throws Exception {
		String forward ="error";	//数据库存数据时出错标记值	
		int flag = 0;
		EndUser user2=(userDao.find(user));
		if (user2!=null && (user2.getUserName().trim()).equals((user.getUserName()).trim())) {
			forward = "error_user"; //用户名已被占用标记标记值
		} else {
			flag = userDao.save(user);
			if (flag == 1) {
				forward = "success"; //成功注册标记值
			}
		}
		return forward;
	}

	public EndUser getUser() {
		return user;
	}

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

3.创建视频组件。
登陆页面
user/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>登陆页面</title>
</head>
<body>
<form method="post" action="/benzhu2/user/logincheck">
		<table>
			<tr>
				<th colspan="2">用户登录</th>
			</tr>
			<tr>
				<td align="right">用户名:</td>
				<td><input type="text" name="user.userName" /></td>
			</tr>
			<tr>
				<td align="right">密码:</td>
				<td><input type="password" name="user.userPassword" /></td>
			</tr>
			<tr>
				<td align="left"><input type="submit" value="登录" /></td>
				<td>未注册者,请先注册,单击 <a href="/benzhu2/user/register.jsp">注册</a></td>
			</tr>

		</table>
	</form>
	<br>
</body>
</html>

登陆成功页面
user/login_success.java

<%@ 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>登陆成功</title>
</head>
<body>
	 欢迎你,${user.userRealName} ,你登入成功!!<br>
	 进入主页面,请点击<a href="/benzhu2/index.jsp">主页面</a>
</body>
</html>

登陆失败页面
user/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-8">
<title>登陆失败</title>
</head>
<body>
<h2 align="center"><font color="red">
                    对不起,你填写的账号和密码不正确!请</font>
       <a href="/benzhu2/user/login.jsp">重新登录</a>!
</h2>
</body>
</html>

注册页面
user/reister.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>注册页面</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("两次密码输入不一致,请重新输入!");			
			return false;
		}else if (userpass.length<=0 ||username.length<=0 ) {
			alert("用户名 以及密码不能为空,请重新输入!");			
			return false;
		}else{
			return true;
		}        
	}
</script>
</head>

<body>
	<h3 align="left">欢迎注册我们的系统,请认真填写您的信息</h3>
	<form name="register" action="/benzhu2/user/register" method="post" onsubmit="return isValidate()">
		<table>
			<tr>
				<td align="right">账户名:</td>
				<td><input type="text" name="user.userName" id="username"></td>
			</tr>
			<tr>
				<td align="right">为您的账户设置密码:</td>
				<td><input type="password" name="user.userPassword" id="userpassword"></td>
			</tr>

			<tr>
				<td align="right">再次确认您的密码:</td>
				<td><input type="password" name="userpass1" id="userpass1"></td>
				<td></td>
			</tr>
			<tr>
				<td align="right">真实姓名:</td>
				<td><input type="text" name="user.userRealName" id="userrealname"></td>
				<td></td>
			</tr>
			<tr>
				<td align="right"><input type="submit" value="提交"></td>
				<td colspan="2"><input type="reset" value="重新填写"></td>
			</tr>
		</table>
	</form>

</body>
</html>

注册成功页面
user/register_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>注册成功!</title>
</head>
<body>
<h3>
	恭喜,${user.userRealName},你成功注册了我们的管理系统!点此
	<a href="/benzhu2/user/login.jsp">登录</a>
</h3>
</body>
</html>

注册失败页面1
user/register_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>注册失败!</title>
</head>
<body>
<h3>对不起,此用户名:${user.userName}已被占用,请重新注册。</h3> <br>
<h2>请点击<a href="/benzhu2/user/register.jsp">注册</a></h2>
</body>
</html>

注册失败页面2
user/register_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>注册失败!</title>
</head>
<body>
<h3>对不起,数据库出错,没有正确保存,请重新注册。</h3> <br>
<h2>请点击<a href="/benzhu2/user/register.jsp">注册</a></h2>
</body>
</html>

系统主页面
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>主页面</title>
</head>
<body>
主页面
</body>
</html>

4.修改web.xml文件。
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>benzhu2</display-name>
  <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>

5.配置Action形成单独的配置文件。
struts-user.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="default" namespace="/user" extends="struts-default">
      
      <action name="register" class="com.action.user.UserAction" method="userRegister" >
            <result name="success">/user/register_success.jsp</result>
            <result name="error">/user/register_failure.jsp</result> 
            <result name="error_user">/user/register_failure_user.jsp</result>           
      </action>
      
      <action name="logincheck" class="com.action.user.UserAction" method="userLogin">
            <result name="failure">/user/login_failure.jsp</result>
            <result name="success">/user/login_success.jsp</result>            
      </action>    
      
    </package>

</struts>

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>
    <include file="struts-user.xml" />
</struts>

6.导入Struts2的必须jar包。
下载文件放入WebContent/WEB-INF/lib文件下并设置好jar包导入
本地下载
注意:此版本为Strut-2.3.24,不支持JDK9.0,支持1.8。
eclipse项目下载: 本地下载

点赞