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

Source: Internet
Author: User
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} <br> Please <a href = "{0}"> Register again </a> error. 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
<! Doctype validators public "-// Apache struts // xwork validator 1.0.2 //" http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd "> <validators> <! -- Verification rules for the user. Username Field --> <field name = "user. username"> <! -- Use the requiredstring validator to ensure that the user. the username field value is neither null nor "" --> <field-validator type = "requiredstring"> <Message key = "error. username. required "/> </field-validator> <! -- Use the stringlength validators to ensure that the user. username field value is between 4 and 12 characters --> <field-validator type = "stringlength"> <! -- Pass the minlength and maxlength parameters to the stringlength validator instance --> <Param name = "minlength"> 4 </param> <Param name = "maxlength"> 12 </param> <message key = "error. username. length "/> </field-validator> </field> <! -- For user. password field validation rules --> <field name = "user. password "> <field-validator type =" requiredstring "> <Message key =" error. password. required "/> </field-validator> <field-validator type =" stringlength "> <Param name =" minlength "> 4 </param> <Param name =" maxlength"> 12 </param> <Message key = "error. password. length "/> </field-validator> </field> <! -- For user. email field verification rules --> <field name = "user. email "> <field-validator type =" requiredstring "> <Message key =" error. email. required "/> </field-validator> <field-validator type =" email "> <Message key =" error. email. invalid "/> </field-validator> </field> </validators>
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
<?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><constant name="struts.enable.DynamicMethodInvocation" value="true" /><package name="default" extends="struts-default"> <actionname="register" class="register.action.RegisterAction"><exception-mapping result="error" exception="java.lang.Exception"/><result name="input">/register.jsp</result><result name="success">/success.jsp</result><result name="error">/error.jsp</result></action></package></struts>

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" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

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 "%> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> 

Error. jsp registration failure page Compilation
<% @ Page Language = "Java" contenttype = "text/html; charset = UTF-8 "pageencoding =" UTF-8 "%> <% @ taglib uri ="/Struts-tags "prefix =" S "%> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <% // 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 () + ":" + reque St. getserverport () + path + "/"; %> <HTML> 


The directory structure of the struts2 application is as follows:
Test:
1. Start the Tomcat server and enter http: // localhost: 8080/struts2-RegisterValidate/register in the address bar! Default. Action: The following content is displayed: Obviously, this is not the expected result. 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:
<actionname="register" class="register.action.RegisterAction"><exception-mapping result="error" exception="java.lang.Exception"/><interceptor-ref name="defaultStack"><param name="validation.excludeMethods">default</param></interceptor-ref><result name="input">/register.jsp</result><result name="success">/success.jsp</result><result name="error">/error.jsp</result></action>
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.