Struts2 Study Notes (3)-use verification frameworks in user registration programs

Source: Internet
Author: User

Struts2 Study Notes (3)-use verification frameworks in user registration programs
Purpose: 1. Use the verification framework to verify user registration information. 2. The user name, password, and email address cannot be blank. 3. Verify the user name and password length. 4. Verify the email address format.
Implementation 1: the basic configuration of the Struts2 application is not described in detail here, specifically the configuration of web. xml and related jar packages.
2. Place the text displayed on the page to the resource file. 1. view all the pages in the User Registration Program, find all the displayed text content, and separate them into the resource file. 2. the same name as the related Action class, with the. preperties extension. The Action class is located in the same package and can only be accessed by this Action
RegisterAction_zh_CN.properties

# Register. the string resource required for the jsp page title = user registration username = user name password = password sex = gender sex. male = male sex. female = female email = email Address pwdQuestion = PASSWORD question pwdAnswer = PASSWORD answer submit = register reset = reset # success. success = successfully registered success.info =$ {user. username}, congratulations on your successful registration # error. the string resource failure = registration failed failure.info = registration failed, because: $ {exception}
Register error again. username. exist = the user name already has an error. username. length =$ {getText ("username")} must contain an error between $ {minLength} and $ {maxLength} characters. password. length = $ {getText ("password")} must contain an error between $ {minLength} and $ {maxLength} characters. email. the invalid =$ {getText ("email")} format is incorrect. username. required =$ {getText ("username")} cannot be empty error. password. required =$ {getText ("password")} cannot be empty error. email. required =$ {getText ("mail")} cannot be blank
The last two pieces of code are added error messages. The OGNL expression is used as the parameter of the message text.
3. Write the authentication file RegisterAction-validation.xml, similarly, with the relevant Action class in the same package
 
 
  
  
   
   
    
   
   
     
    
    4
    12
    
   
  
  
  
   
    
   
   
    4
    12
    
   
  
  
  
   
    
   
   
    
   
  
  
1) when writing a verification file, you should note that the DTD statement prompts the following error when I first input the DTD version on the textbook:
The file cannot be validated as the XML definition "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd" that is specified as describing the syntax of the file cannot be located.
Later, I found a solution on the Internet and replaced it with the correct version above.

IV. Other related Action classes, page compilation, and other registeractions
package register.action;import java.sql.SQLException;import java.util.Date;import register.dao.UserDao;import register.entity.User;import register.exceptions.UsernameExistException;import com.opensymphony.xwork2.ActionSupport;public class RegisterAction extends ActionSupport {/** *  */private static final long serialVersionUID = 1L;private User user;private UserDao userdao;public RegisterAction(){userdao=new UserDao();}@Overridepublic String doDefault()throws Exception{return INPUT;}@Overridepublic String execute() throws SQLException, UsernameExistException{user.setRegDate(new Date());try{userdao.register(user);}catch(UsernameExistException e){addFieldError("user.username",getText("error.username.exist"));return INPUT;}return SUCCESS;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}}

User entity class: User
package register.entity;import java.io.Serializable;import java.util.Date;public class User implements Serializable {/** *  */private static final long serialVersionUID = 1L;private Integer id;private String username;private String password;private Boolean sex;private String email;private String pwdQuestion;private String pwdAnswer;private Date regDate;private Date lastLoginDate;private String lastLoginIp;public Integer getId() {return id;}public void setId(Integer 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 Boolean getSex() {return sex;}public void setSex(Boolean sex) {this.sex = sex;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getPwdQuestion() {return pwdQuestion;}public void setPwdQuestion(String pwdQuestion) {this.pwdQuestion = pwdQuestion;}public String getPwdAnswer() {return pwdAnswer;}public void setPwdAnswer(String pwdAnswer) {this.pwdAnswer = pwdAnswer;}public Date getRegDate() {return regDate;}public void setRegDate(Date regDate) {this.regDate = regDate;}public Date getLastLoginDate() {return lastLoginDate;}public void setLastLoginDate(Date lastLoginDate) {this.lastLoginDate = lastLoginDate;}public String getLastLoginIp() {return lastLoginIp;}public void setLastLoginIp(String lastLoginIp) {this.lastLoginIp = lastLoginIp;}}

Operation on the database of the registered user. UserDao
package register.dao;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import register.entity.User;import register.exceptions.UsernameExistException;public class UserDao {public UserDao(){String driverClass="com.mysql.jdbc.Driver";try{Class.forName(driverClass);}catch(ClassNotFoundException ce){ce.printStackTrace();}}public Connection getConnection() throws SQLException{Stringurl="jdbc:mysql://localhost:3307/user";Stringuser="tankcat_2";Stringpw="wxt222$$$";return DriverManager.getConnection(url,user,pw);}public User register(User user) throws SQLException, UsernameExistException{Connection conn=null;PreparedStatement pstmt=null;ResultSet rs=null;try{conn=getConnection();String sql="select * from reg_user where username = ?";pstmt=conn.prepareStatement(sql);pstmt.setString(1, user.getUsername());rs=pstmt.executeQuery();if(rs.next()){throw new UsernameExistException();}sql="insert into reg_user(username,password,sex,email,pwd_question,pwd_answer,reg_date) values(?,?,?,?,?,?,?)";pstmt=conn.prepareStatement(sql);pstmt.setString(1, user.getUsername());pstmt.setString(2, user.getPassword());pstmt.setBoolean(3, user.getSex());pstmt.setString(4, user.getEmail());pstmt.setString(5, user.getPwdQuestion());pstmt.setString(6,user.getPwdAnswer());pstmt.setTimestamp(7, new java.sql.Timestamp(user.getRegDate().getTime()));pstmt.execute();rs=pstmt.executeQuery("select last_insert_id()");if(rs.next()){user.setId(rs.getInt(1));}else{return null;}}catch(SQLException se){throw se;}finally{closeResultSet(rs);closePreparedStatement(pstmt);closeConnection(conn);}return user;}private void closeResultSet(ResultSet rs) {// TODO Auto-generated method stubif(rs!=null){try{rs.close();}catch(SQLException se){se.printStackTrace();}rs=null;}}private void closePreparedStatement(PreparedStatement pstmt) {// TODO Auto-generated method stubif(pstmt!=null){try{pstmt.close();}catch(SQLException se){se.printStackTrace();}pstmt=null;}}private void closeConnection(Connection conn) {// TODO Auto-generated method stubif(conn!=null){try{conn.close();}catch(SQLException se){se.printStackTrace();}conn=null;}}}

Struts. xml file configuration
 
 
  
   
   
   
    /register.jsp
   
   
    /success.jsp
   
   
    /error.jsp
   
  
 

Compiling the registration page of register. jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %>
 <s:text name="title"/>
 
 
 
  
  
  
  
  
  
  
  
 

Writing on the successful registration page of succes. jsp
<% @ Page language = "java" contentType = "text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%> <% @ taglib uri ="/struts-tags "prefix =" s "%>
 Welcome Page
 , Welcome

Error. jsp registration failure page Compilation
<% @ Page language = "java" contentType = "text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%> <% @ taglib uri ="/struts-tags "prefix =" s "%><% // String path = request. getContextPath (); // String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; // obtain the context path of the Web application String path = request. getContextPath (); // construct the complete URLString basePath = request for the Web application context path. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %>
 <S: text name = "failure"/>
 
  
   
<% = BasePath %> register! Default. action
  
 


The directory structure of the Struts2 application is as follows:
Test:
1. Start the Tomcat server and enter http: // localhZ success? In the address bar? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> keys" http://www.2cto.com/uploadfile/Collfiles/20140809/20140809090526144.png "alt =" \ "> apparently, this is not the result we want, when a user accesses the registration page rather than submitting a registry ticket, verification is not required. The reason for this is that you are calling Register. The verification framework was called before the doDefault method of Action. Since the interceptor that calls the verification framework is validation, rather than workflow, We can configure the exclusion method for the validation Interceptor. The changes are as follows:
 
 
  default
 
 
  /register.jsp
 
 
  /success.jsp
 
 
  /error.jsp
 
Restart Tomcat and test the user registration program again.






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.