• Struts2+MySQL登录注册


    下载地址:http://download.csdn.net/detail/qq_33599520/9777172

    项目结构图:

    代码:

    package com.mstf.action;
    
    import java.util.List;
    
    import com.mstf.entiity.User;
    import com.mstf.service.UserBiz;
    
    public class UserAction {  // 控制器
    	private UserBiz userBiz;
    	private User user;
    	private String msg;
    	
    	public String getMsg() {
    		return msg;
    	}
    	public void setMsg(String msg) {
    		this.msg = msg;
    	}
    	
    	List<User> users;
    	
    	public User getUser() {
    		return user;
    	}
    	public void setUser(User user) {
    		this.user = user;
    	}
    	public List<User> getUsers() {
    		return users;
    	}
    	public void setUsers(List<User> users) {
    		this.users = users;
    	}
    	
    	// 用户登录的方法
    	public String login(){
    		userBiz = new UserBiz();
    		if(userBiz.validateUser(user))
    			return "welcome";
    		else{
    			msg = "请重新登陆";
    			return "error";
    		}
    	}
    	
    	// 用户注册的方法
    	public String regist(){
    		userBiz = new UserBiz();
    		if(userBiz.registUser(user))
    			return "sucess";
    		else{
    			msg = "注册失败,请重新登陆";
    			return "fall";
    		}
    	}
    	
    	// 显示所有注册用户的方法
    	public String showUsers(){
    		userBiz = new UserBiz();
    		users = userBiz.findAllUsers();
    		return "welcome";
    	}
    }
    

      

    package com.mstf.dao;
    
    
    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.mstf.db.DbHelper;
    import com.mstf.entiity.User;
    
    public class UserDAO {  // 用户的dao
    	
    	// 用户登录
    	public boolean checkUser(User user){
    		Connection conn = DbHelper.getConnection();
    		String sql = "select * from admin where `userName`=? and `passWord`=?";
    		try {
    			 PreparedStatement pstmt = conn.prepareStatement(sql);
    			 pstmt.setString(1, user.getUserName());
    			 pstmt.setString(2, user.getPassWord());
    			 ResultSet rs = pstmt.executeQuery();
    			 if(rs.next())
    				return true;
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return false;
    	}
    	
    	// 用户注册
    	public boolean saveUser(User user){
    		Connection conn = DbHelper.getConnection();
    		String sql = "insert into admin values(null,?,?)";
    		try {
    			 PreparedStatement pstmt = conn.prepareStatement(sql);
    			 pstmt.setString(1, user.getUserName());
    			 pstmt.setString(2, user.getPassWord());
    			 int num = pstmt.executeUpdate();
    			 if(num>0)
    				return true;
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return false;
    	}
    	
    	// 显示所有注册用户
    	public List<User> findAllUsers(){
    		Connection conn = DbHelper.getConnection();
    		String sql = "select * from admin";
    		List<User> users = new ArrayList<User>();
    		try {
    			 PreparedStatement pstmt = conn.prepareStatement(sql);
    			 ResultSet rs = pstmt.executeQuery();
    			 while(rs.next()){
    				 User user = new User();
    				 user.setId(rs.getInt("id"));
    				 user.setUserName(rs.getString("userName"));
    				 user.setPassWord(rs.getString("passWord"));
    				 users.add(user);
    			 }
    						 
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return users;
    	}
    }
    

      

    package com.mstf.db;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DbHelper {
    	private static String url = "jdbc:mysql://localhost:3306/test";  //数据库地址
    	private static String userName = "root";  //数据库用户名
    	private static String passWord = "root";  //数据库密码
    	private static Connection conn;
    	
    	private DbHelper(){
    		
    	}
    	
    	public static Connection getConnection(){
    		if(null == conn){
    			try {
    				Class.forName("com.mysql.jdbc.Driver");
    				conn = DriverManager.getConnection(url, userName, passWord);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    		return conn;
    	}
    	
    	public static void main(String[] args) {  //测试数据库是否连通
    		System.err.println(getConnection());
    	}
    }
    

      

    package com.mstf.entiity;
    
    public class User {  // 实体类
    	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;
    	}
    	public User(){
    			
    	}
    }
    

      

    package com.mstf.filter;
    
    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    public class LoginFilter extends HttpServlet implements Filter {  // 登录过滤器
    
    	private static final long serialVersionUID = 1L;
    
    	public void destroy() {
        }
    
        public void doFilter(ServletRequest srq, ServletResponse srp, FilterChain filterChain) throws IOException, ServletException{
            
            HttpServletRequest request = (HttpServletRequest) srq;      
            HttpServletResponse response = (HttpServletResponse) srp;      
            HttpSession session = request.getSession();      
            String url=request.getServletPath();  
            String contextPath=request.getContextPath();  
            if(url.equals("")) url+="/";  
            if((url.startsWith("/")&&!url.startsWith("/index.jsp"))){//若访问后台资源 过滤到login  
                 String userName=(String)session.getAttribute("userName");  
                 if(userName==null){//转入管理员登陆页面  
                      response.sendRedirect(contextPath+"/index.jsp"); 
                      return;  
                 }  
            }  
              filterChain.doFilter(srq, srp);    
        }  
    
        public void init(FilterConfig arg0) throws ServletException {
    
        }
    }
    

      

    package com.mstf.service;
    
    import java.util.List;
    
    import com.mstf.dao.UserDAO;
    import com.mstf.entiity.User;
    
    public class UserBiz {  // 业务层(服务层/逻辑处理层)
    	private UserDAO userDao;
    	
    	// 验证用户登录是否合法
    	public boolean validateUser(User user){
    		userDao = new UserDAO();
    		// 业务层调用DAO的具体方法
    		return userDao.checkUser(user);
    	}
    		
    	// 用户用户注册
    	public boolean registUser(User user){
    		userDao = new UserDAO();
    		return userDao.saveUser(user);
    	}
    	
    	// 获得所有注册用户
    	public List<User> findAllUsers(){
    		userDao = new UserDAO();
    		return userDao.findAllUsers();
    	}
    }
    

      

    <?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="test" namespace="/"  extends="struts-default">
            <action name="login" class="com.mstf.action.UserAction" method="login">
    			<result name="welcome" type="redirectAction">
    				<param name="actionName">showUsers</param>
    			</result>
    			<result name="error">/error.jsp</result>
    		</action>
    		<action name="regist" class="com.mstf.action.UserAction" method="regist">
    			<result name="sucess">/sucess.jsp</result>
    			<result name="fall">/fall.jsp</result>
    		</action>
    		<action name="showUsers" class="com.mstf.action.UserAction" method="showUsers">
    			<result name="welcome">/welcome.jsp</result>
    		</action>
        </package>
    
    </struts>
    

      

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.0" 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_3_0.xsd">
    
        <display-name></display-name>
        
        <!-- 起始页面 -->
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    
        <!-- 过滤器 用于初始化struts2 -->
        <filter>
            <filter-name>struts2</filter-name>
            <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        </filter>
    
        <!-- 用于struts2 的过滤器映射 -->
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        
        <!-- 登陆验证过滤器 -->
        <filter>
             <filter-name>loginFilter</filter-name>
             <filter-class>com.mstf.filter.LoginFilter</filter-class>
        </filter>
    	<filter-mapping>
             <filter-name>loginFilter</filter-name>
    
             <url-pattern>/error.jsp</url-pattern>
             <url-pattern>/fall.jsp</url-pattern>
             <url-pattern>/sucess.jsp</url-pattern>
             <url-pattern>/welcome.jsp</url-pattern>
    	</filter-mapping> 
    </web-app>
    

      

    <%@ 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>
    	<h1>用户名或密码错误!请重新登录。</h1>
    	<a href="index.jsp">返回后台管理首页</a>
    </body>
    </html>
    

      

    <%@ 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>
    	<h1>很遗憾,注册失败!</h1>
    	<a href="index.jsp">返回后台管理首页</a>
    </body>
    </html>
    

      

    <%@ 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 action="login" method="post">
    		<table>
    			<tr>
    				<td>帐号:
    					<input type="text" name="user.userName" maxlength="16">
    				</td>
    			</tr>
    			<tr>
    				<td>密码:
    					<input type="password" name="user.passWord" maxlength="16">
    				</td>
    			</tr>
    			<tr>
    				<td>
    					<input type="submit" value="登录">
    				</td>
    				<td>
    					<a href="regeist.jsp">注册</a>
    				</td>
    			</tr>
    		</table>
    	</form>
    </body>
    </html>
    

      

    <%@ 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 action="regist" method="post" onsubmit="return check(this);">
    		<table>
    			<tr>
    				<td>帐号:
    					<input type="text" name="user.userName" maxlength="16">
    				</td>
    			</tr>
    			<tr>
    				<td>输入密码:
    					<input type="password" name="user.passWord" maxlength="16">
    				</td>
    			</tr>
    			<tr>
    				<td>
    					<input type="submit" value="注册">
    				</td>
    				<td>
    					<a href="index.jsp">返回登录</a>
    				</td>
    			</tr>
    		</table>
    	</form>
    </body>
    </html>
    

      

    <%@ 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>
    	<h1>恭喜您,${user.userName }注册成功!</h1>
    	<a href="index.jsp">返回后台管理首页登录</a>
    </body>
    </html>
    

      

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!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>
    	<h1>欢迎${user.userName }登录成功!</h1>
    	<br><br>
    	<h2>已经注册的用户:</h2>
    	<br>
    	<table border="1px" width="600px" align="center">
    			<tr>
    				<td>
    					ID:
    				</td>
    				<td>
    					用户名:
    				</td>
    				<td>
    					密码:
    				</td>
    			</tr>
    			<c:forEach items="${users }" var="user">
    				<tr>
    					<td>
    						${user.id }
    					</td>
    					<td>
    						${user.userName }
    					</td>
    					<td>
    						${user.passWord }
    					</td>
    				</tr>
    			</c:forEach>
    	</table>
    	<a href="index.jsp">返回后台管理首页</a>
    </body>
    </html>
    

      下载地址:http://download.csdn.net/detail/qq_33599520/9777172

  • 相关阅读:
    字体大小(几号-几磅
    基于有限差分的偏移方法与基于相移方法的区别
    ubuntu aptget install problem
    su安装
    石油、天然气、地质类投稿刊物及邮箱
    ubuntu添加中文输入法
    C#使用Quartz.NET详细讲解
    Using Developer Dashboard in SharePoint 2010
    Windows Server AppFabric 使用
    列出联接和投影
  • 原文地址:https://www.cnblogs.com/ceet/p/6531876.html
Copyright © 2020-2023  润新知