struts2框架实现登录注册注销,后台验证+mysql密码加密

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/warmwine/article/details/79944990

struts2框架实现登录注册注销,后台验证+mysql密码加密

any question or wanna codes, just contact with me by loooln@126.com

If u're walking down 2 the right path and u're willing 2 keep walking, eventually u'll make progress! 与君共勉

简介

项目利用Struts2框架实现了用户的登录注册以及注销功能。注册过程中服务端会对数据表进行校验并对密码进行加密,最后用户经过注册将数据表提交到数据库。登录过程中用Struts2的另一种校验方式对账号密码进行服务端校验。(也可以通过js在前台进行校验,不作赘述)

项目环境

Eclipse(maven project)

mysql

tomcat v9.0

项目界面

1. 登录界面


2.注册页面

3.项目目录(忽略报错,报错原因是因为web工程转maven重构目录了,无影响的)


后台代码实现

1. 建立数据库表

  CREATE TABLE `user` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `userName` varchar(25) NOT NULL,
    `password` blob NOT NULL,
    `trueName` varchar(32) DEFAULT NULL,
    `sex` int(11) DEFAULT NULL,
    `email` varchar(45) DEFAULT NULL,
    PRIMARY KEY (`id`)
  ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8

2.pom.xml

  
  <project xmlns="http://maven.apache.org/POM/4.0.0" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>UseStruts</groupId>    
      <artifactId>UseStruts</artifactId>
      <version>1.0.0</version>    
      <packaging>war</packaging>  
      <dependencies>
          <!-- 配置structs所需的jar @{ -->
          <dependency>
              <groupId>org.apache.struts</groupId>
              <artifactId>struts2-core</artifactId>
              <version>${struts2Ver}</version>
              <exclusions>
                  <exclusion>
                      <artifactId>javassist</artifactId>
                      <groupId>javassist</groupId>
                  </exclusion>
                  <exclusion>
                      <artifactId>commons-io</artifactId>
                      <groupId>commons-io</groupId>                                       
                  </exclusion>
              </exclusions>
          </dependency>
          <dependency>
              <groupId>org.apache.struts</groupId>
              <artifactId>struts2-json-plugin</artifactId>
              <version>${struts2Ver}</version>
          </dependency>   
          <dependency>
              <groupId>org.apache.struts</groupId>
              <artifactId>struts2-convention-plugin</artifactId>
              <version>${struts2Ver}</version>
          </dependency>
          <!-- }@ 配置structs所需的jar -->
          
          <!-- 配置日志所需的jar @{ -->
          <dependency>
              <groupId>log4j</groupId>
              <artifactId>log4j</artifactId>
              <version>1.2.17</version>
          </dependency>       
          <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-api</artifactId>
              <version>${log4jVer}</version>
          </dependency>
          <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-core</artifactId>
              <version>${log4jVer}</version>
          </dependency>
          <dependency>
              <groupId>org.apache.logging.log4j</groupId>
              <artifactId>log4j-1.2-api</artifactId>
              <version>${log4jVer}</version>
          </dependency>       
          <!-- }@ 配置日志所需的jar -->
          
          <dependency>
              <groupId>commons-logging</groupId>
              <artifactId>commons-logging-api</artifactId>
              <version>1.1</version>
          </dependency>
  <!--        
          <dependency>
              <groupId>org.eclipse.jdt.core.compiler</groupId>
              <artifactId>ecj</artifactId>
              <version>4.6.1</version>
          </dependency>
   -->        
          <dependency>
              <groupId>javax</groupId>
              <artifactId>javaee-api</artifactId>
              <version>8.0</version>
          </dependency>
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.46</version>
          </dependency>
          <dependency>
              <groupId>commons-io</groupId>
              <artifactId>commons-io</artifactId>
              <version>2.4</version>
          </dependency>       
      </dependencies>
      
      <build>
          <sourceDirectory>src/main</sourceDirectory>
          <finalName>UseStruts</finalName>
          <resources>
              <resource>
                  <directory>src/main/java</directory>
                  <excludes>
                      <exclude>**/*.java</exclude>
                  </excludes>
              </resource>
              <resource>
                  <directory>src/main/resources</directory>
              </resource>
          </resources>        
          <plugins>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>3.7.0</version>
                  <configuration>
                      <source>1.8</source>
                      <target>1.8</target>
                      <encoding>utf-8</encoding>
                  </configuration>
              </plugin>           
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-war-plugin</artifactId>
                  <version>3.0.0</version>
                  <configuration>
                      <warSourceDirectory>WebContent</warSourceDirectory>
                      <failOnMissingWebXml>false</failOnMissingWebXml>
                  </configuration>
              </plugin>
          </plugins>
      </build>    
      <properties>
          <log4jVer>2.9.1</log4jVer>
          <struts2Ver>2.5.16</struts2Ver>                 
      </properties>   
  </project>

3. javabean(User)

  package com.ruc.bean;
  
  public class User {
      private String userName;
      private String password;
      private String name;
      private String email;
      /**
       * @return the userName
       */
      public String getUserName() {
          return userName;
      }
      /**
       * @param userName the userName to set
       */
      public void setUserName(String userName) {
          this.userName = userName;
      }
      /**
       * @return the password
       */
      public String getPassword() {
          return password;
      }
      /**
       * @param password the password to set
       */
      public void setPassword(String password) {
          this.password = password;
      }
      /**
       * @return the name
       */
      public String getName() {
          return name;
      }
      /**
       * @param name the name to set
       */
      public void setName(String name) {
          this.name = name;
      }
      /**
       * @return the email
       */
      public String getEmail() {
          return email;
      }
      /**
       * @param email the email to set
       */
      public void setEmail(String email) {
          this.email = email;
      }   
  }
  

5.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>UseStruts</display-name>
    <welcome-file-list>
      <welcome-file>Login.jsp</welcome-file>
    </welcome-file-list>
    <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
  </web-app>

6.数据连接(此处需要修改数据库配置)

  
  package com.ruc.tools;
  
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.SQLException;
  
  public class DBConn {
      private static String dbDriver ="com.mysql.jdbc.Driver";
      
      public static Connection getConnection() {
          //加载连接数据库到虚拟机
          try {
              Class.forName(dbDriver);
          } catch (ClassNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          
          //取得数据库连接
          String url = "jdbc:mysql://localhost:3306/userManager?useUnicode&characterEncoding=UTF-8&useSSL=false";
          try {
              Connection conn = DriverManager.getConnection(url,"root","");
              conn.setAutoCommit(false);
              return conn;
          } catch (SQLException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          
          return null;
      }
  }

7.User Dao层

  
  package com.ruc.dao;
  
  import java.sql.Connection;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  
  import com.ruc.bean.User;
  import com.ruc.tools.DBConn;
  
  public class UserDao {
      
      public User userLogin(String userName,String password) {
          
          Connection conn = null;
          PreparedStatement ps = null;
          ResultSet rs = null;
          User user = null;
          
          //connect the mysql
          
          conn = DBConn.getConnection();
          //通过mysql的encode函数对密码字段进行加密。
          String sqlCheck = "select * from user where userName=? and password = encode(?,\"web18\")";
          
          
          try {
              ps = conn.prepareStatement(sqlCheck);
              ps.setString(1, userName);
              ps.setString(2, password);
              rs = ps.executeQuery();
              if(rs.next()) {
                  user = new User();
                  user.setUserName(rs.getString("userName"));
                  user.setPassword(rs.getString("password"));
              }
          }catch(SQLException e) {
              e.printStackTrace();
              System.out.println("登录异常!!!");
          }finally {
              try {
                  //此处应该封装
                  conn.close();
                  ps.close();
                  rs.close();
              } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  System.out.println("关闭异常");
              }
          }
          
          return user;
      }
      
      public int register(User user) {
          int i = 0;
          Connection conn = null;
          PreparedStatement ps = null;
          
          conn = DBConn.getConnection();
          // "前加一个/是将"进行转义,用单引号也可以
          String sql_insert = "insert into user(userName,password,trueName,email) values (?,encode(?,\"web18\"),?,?);";
          
          try {
              ps = conn.prepareStatement(sql_insert);
              ps.setString(1, user.getUserName());
              System.out.println(user.getUserName());
              ps.setString(2, user.getPassword());
              ps.setString(3, user.getName());
              ps.setString(4, user.getEmail());
              i = ps.executeUpdate();
              conn.commit();
          } catch (SQLException e) {
              // TODO Auto-generated catch block
              System.out.println("注册失败!");
              e.printStackTrace();
          }finally {
              try {
                  conn.close();
                  ps.close();
              } catch (SQLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
              return i;
          }
  
  }
  

8.LoginAction(LoginMDAction)

  package com.ruc.actions;
  
  import com.opensymphony.xwork2.ActionContext;
  import com.opensymphony.xwork2.ActionSupport;
  import com.opensymphony.xwork2.ModelDriven;
  import com.ruc.bean.User;
  import com.ruc.dao.UserDao;
  
  public class LoginAction extends ActionSupport implements ModelDriven<User> {
  
      private static final long serialVersionUID = 1L;
      private User user = new User();
      private UserDao userDao = new UserDao();
  
      //getModel():Gets the model to be pushed onto the ValueStack instead of the Action itself.
      @Override
      public User getModel() {
          // TODO Auto-generated method stub
          return user;
      }
  
      public String execute() {
          return "";
      }
  
      public String login() {
          User usr = userDao.userLogin(user.getUserName(), user.getPassword());
  
          if (null == usr)
              return "error";
          else {
              ActionContext.getContext().getSession().put("user", usr);
              return "success";
          }
      }
  
  }
  

9.LoginOut(注销Action)

  
  package com.ruc.actions;
  
  import com.opensymphony.xwork2.ActionContext;
  import com.opensymphony.xwork2.ActionSupport;
  
  public class LoginOut extends ActionSupport {
      //注销
      public String execute() {
          Object obj = ActionContext.getContext().getSession().get("user");
          if(obj != null) {
              ActionContext.getContext().getSession().clear();    
          }
          return "out";
      }
  }

10.RegisterMDAction(注销Action,继承ModelDriven<User>)(Struts2第一种校验方式)

  package com.ruc.actions;
  
  import java.util.regex.Matcher;
  import java.util.regex.Pattern;
  
  import com.opensymphony.xwork2.ActionSupport;
  import com.opensymphony.xwork2.ModelDriven;
  import com.ruc.bean.User;
  import com.ruc.dao.UserDao;
  
  public class RegisterMDAction extends ActionSupport implements ModelDriven {
      
      private User user = new User();
      private UserDao userDao= null;
      @Override
      public Object getModel() {
          // TODO Auto-generated method stub
          return user;
      }
      
      public String execute() {
          return "";
      }
      
      public String register() {
          userDao = new UserDao();
          int i = userDao.register(user);
          System.out.println(i);
          
          if(i!=0) {
              return SUCCESS;
          }else {
              return ERROR;
          }
      }
      
      //第一种校验,方法名格式:validate+Action方法名
      public void validateRegister() {
          if(user.getUserName().equals("") || user.getUserName() == null) {
              System.out.println("validate running");
              addFieldError("userName","UserName cannot be null");
          }
          if(user.getUserName().length()<6 || user.getUserName().length() >18) {
              addFieldError("userName","UserName limit the length of 6 to 18");
          }
          
          if(user.getPassword().equals("") || user.getPassword() == null) {
              System.out.println("validate running");
              addFieldError("password","password cannot be null");
          }
          if(user.getPassword().length()<6 || user.getPassword().length() >18) {
              addFieldError("password","password limit the length of 6 to 18");
          }
          
          //通过正则表达式来验证邮箱格式
          boolean flag = false;
          String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
          Pattern regex = Pattern.compile(check);
          Matcher matcher = regex.matcher(user.getEmail());
          flag = matcher.matches();
          
          if(!flag)
              addFieldError("email","pattern of email wrong!");
      }
  }

11.对登录用户名的校验,此xml文件命名格式为XXX-validation.xml,XXX是相对应Action文件的类名,并且必须将此文件放在与相应的Action相同目录下。(本人在此处吃了亏,记忆深刻)(Struts2第二种校验方式)

  
  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE validators PUBLIC
          "-//Apache Struts//XWork Validator 1.0.2//EN"
          "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
  <validators>
      <field name="userName">
          <field-validator type="requiredstring">
              <message>the name should not null</message>
          </field-validator>
          <field-validator type="stringlength">
              <param name="minLength">6</param>
              <param name="maxLength">18</param>
              <message>用户名长度要在6--18位之间</message>
          </field-validator>
      </field>
  </validators>

12.struts.xml的配置

  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE struts PUBLIC
      "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
      "http://struts.apache.org/dtds/struts-2.5.dtd">
  <struts>
      <package name="struts2" namespace="/" extends = "struts-default">
          <!-- 添加默认打开页面 在web.xml中已经配置了 -->
          <!-- <default-action-ref name="index"></default-action-ref> 
          <action name="index"> 
              <result type="dispatcher">/Login.jsp</result> 
          </action>  -->
          
          
          <action name="userlogin" class = "com.ruc.actions.LoginAction" method="login">
              <result name="input">Login.jsp</result>
              <result name="error" type="redirect">Error.jsp</result>
              <result name="success">Welcome.jsp</result>
          </action>
          
          <action name="loginout" class="com.ruc.actions.LoginOut">
              <result name="out" type="redirect">Login.jsp</result>
          </action>
          
          <action name="register" class="com.ruc.actions.RegisterMDAction" method="register" >
              <result name="input">Register.jsp</result>
              <result name="success">Login.jsp</result>
              <result name="error">RegisterError.jsp</result>
          </action>
      </package>
  </struts>

前台界面(样式文件省略,样式在网上下载)

1.Login.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 lang="en" class="no-js">
  <head>
  <meta charset="UTF-8" />
  <title>login</title>
  <s:head />
  </head>
  <body>
      <div>
          <div>
              <div>
                  <div class="logo_box">
                      <h3>欢迎你</h3>
                      <s:fielderror />
                      <form action="userlogin" method="post">
                          <div class="input_outer">
                              <span class="u_user"></span> <input name="userName" class="text"
                                  style="color: #FFFFFF !important" type="text"
                                  placeholder="请输入账户">
                          </div>
                          <div class="input_outer">
                              <span class="us_uer"></span> <input name="password" class="text"
                                  style="color: #FFFFFF !important; position: absolute; z-index: 100;"
                                  value="" type="password" placeholder="请输入密码">
                          </div>
                          <div class="mb2">
                              <input class="act-but submit" type="submit" value="登录"
                                  style="color: #FFFFFF; width: 210px; position: relative; left: 20%" />
                              <span><input class="act-but submit" type="button"
                                  value="注册" onclick='window.location.href="Register.jsp"'
                                  style="color: #FFFFFF; width: 210px; position: relative; left: 20%" /></span>
                          </div>
                      </form>
                  </div>
              </div>
          </div>
      </div>
  </body>
  </html>

2.Register.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">
  </head>
  <body>
      <div class="container demo-1">
          <div class="content">
              <div id="large-header" class="large-header">
                  <canvas id="demo-canvas"></canvas>
                  <div class="logo_box" style="top:35%">
                      <h3>注册页面</h3>
                      <form action="register" method="post">
                              <s:fielderror><s:param>userName</s:param></s:fielderror>
                          <div class="input_outer">
                              <span class="u_user"></span> <input name="userName" class="text"
                                  style="color: #FFFFFF !important" type="text"
                                  placeholder="请输入登录用户名">
                          </div>
                              <s:fielderror><s:param>password</s:param></s:fielderror>
                          <div class="input_outer">
                              <span class="us_uer"></span> <input name="password" class="text"
                                  style="color: #FFFFFF !important; position: absolute; z-index: 100;"
                                  value="" type="password" placeholder="请输入密码">
                          </div>
                          <div class="input_outer">
                              <span class="u_user"></span> <input name="trueName" class="text"
                                  style="color: #FFFFFF !important" type="text"
                                  placeholder="请输入姓名">
                          </div>
                              <s:fielderror><s:param>email</s:param></s:fielderror>
                          <div class="input_outer">
                              <span class="u_email"></span> <input name="email" class="text"
                                  style="color: #FFFFFF !important" type="text"
                                  placeholder="请输入电子邮箱">
                          </div>
                          <div class="mb2">
                              <input class="act-but submit" type="submit" value="注册"
                                  style="color: #FFFFFF; width: 210px; position: relative; left: 20%" />
                              <input class="act-but submit" type="reset" value="重置"
                                  style="color: #FFFFFF; width: 210px; position: relative; left: 20%" />
                          </div>
                      </form>
                  </div>
              </div>
          </div>
      </div>
  
  </body>
  </html>

3.Error.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>登录失败</title>
  </head>
  <body>
      <h1>
      <S:text name="用户名或密码错误!"></S:text>
      </h1>
  </body>
  </html>

4.RegisterError.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>
      <hr/>
      <a href="Login.jsp">重新登录</a><br/>
      <a href="Register.jsp">重新注册</a>
  </body>
  </html>

5.Welcome.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>登录成功</title>
  </head>
  <body>
      <h2>
      <%-- <%= session.getAttribute("user") %> --%>
      <S:property value="#session.user.userName" />   ,欢迎登录!
      <S:form action="loginout">
          <S:submit value="zhuxiao"></S:submit>
      </S:form>
      </h2>
  </body>
  </html>

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页