struts2学习笔记—— 在用户注冊程序中使用验证框架
Posted cxchanpin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts2学习笔记—— 在用户注冊程序中使用验证框架相关的知识,希望对你有一定的参考价值。
实现目标:
详细实现
一、Struts2应用的基础配置
二、将页面显示的文本内容放到资源文件里
#register.jsp页面所需的字符串资源 title=用户注冊 username=用户名 password=密码 sex=性别 sex.male=男 sex.female=女 email=邮件地址 pwdQuestion=密码问题 pwdAnswer=密码答案 submit=注冊 reset=重置 #success.jsp页面所需的字符串资源 success=注冊成功 success.info=${user.username},恭喜你注冊成功 #error.jsp页面所需的字符串资源 failure=注冊失败 failure.info=注冊失败,原因是:${exception}<br>请<a href="{0}">又一次注冊</a> error.username.exist=用户名已经存在 error.username.length=${getText("username")}长度必须在${minLength}到${maxLength}个字符之间 error.password.length=${getText("password")}长度必须在${minLength}到${maxLength}个字符之间 error.email.invalid=${getText("email")}格式不正确 error.username.required=${getText("username")}不能为空 error.password.required=${getText("password")}不能为空 error.email.required=${getText("mail")}不能为空
三、编写验证文件
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd"> <validators> <!-- 针对user.username字段的验证规则 --> <field name="user.username"> <!-- 使用requiredstring验证器。确保user.username字段值不为null,也不为“” --> <field-validator type="requiredstring"> <message key="error.username.required"/> </field-validator> <!-- 使用stringlength验证器。确保user.username字段值的字符长在4到12之间 --> <field-validator type="stringlength"> <!-- 向stringlength验证器实例传递minLength和maxLength參数 --> <param name="minLength">4</param> <param name="maxLength">12</param> <message key="error.username.length"/> </field-validator> </field> <!-- 针对user.password字段的验证规则 --> <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> <!-- 针对user.email字段的验证规则 --> <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).在编写验证文件时要注意。DTD的声明,我一開始对着教材上的DTD版本号输入,运行的时候发现提示了一个错误例如以下:
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.后来在网上找到了解决方式,替换成上面正确的版本号就能够了。
四、其它相关Action类、页面的编写等
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(); } @Override public String doDefault()throws Exception{ return INPUT; } @Override public 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
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; } }
对注冊用户的数据库操作.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{ String url="jdbc:mysql://localhost:3307/user"; String user="tankcat_2"; String pw="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 stub if(rs!=null){ try{ rs.close(); }catch(SQLException se){ se.printStackTrace(); } rs=null; } } private void closePreparedStatement(PreparedStatement pstmt) { // TODO Auto-generated method stub if(pstmt!=null){ try{ pstmt.close(); }catch(SQLException se){ se.printStackTrace(); } pstmt=null; } } private void closeConnection(Connection conn) { // TODO Auto-generated method stub if(conn!=null){ try{ conn.close(); }catch(SQLException se){ se.printStackTrace(); } conn=null; } } }
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> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="default" extends="struts-default"> <action name="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>
<%@ 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><s:text name="title"/></title> </head> <body> <hr color="#ededed"/> <s:fielderror/> <s:form action="register.action"> <s:textfield name="user.username" key="username"/> <s:password name="user.password" key="password"/> <s:radio name="user.sex" value="true" list="#{true:getText(‘sex.male‘),false:getText(‘sex.female‘)}" key="sex"/> <s:textfield name="user.email" key="email"/> <s:textfield name="user.pwdQuestion" key="pwdQuestion"/> <s:textfield name="user.pwdAnswer" key="pwdAnswer"/> <s:submit key="submit"/> <s:reset key="reset"/> </s:form> </body> </html>
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> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>欢迎界面</title> </head> <body> <s:property value="user.username"/>。欢迎 </body> </html>
error.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"> <% //String path = request.getContextPath(); //String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; //得到Web应用程序的上下文路径 String path=request.getContextPath(); //构建Web应用程序上下文路径的完整URL String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><s:text name="failure"/></title> </head> <body> <s:text name="failure.info"> <s:param><%=basePath %>register!default.action</s:param> </s:text> </body> </html>
该Struts2应用程序的文件夹结构例如以下图:
Action的doDefault方法之前。验证框架被调用了。
<action name="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>重新启动Tomcat,再次測试用户注冊程序。此时一切执行正常
以上是关于struts2学习笔记—— 在用户注冊程序中使用验证框架的主要内容,如果未能解决你的问题,请参考以下文章