浅谈Struts2验证框架及用户注册
时间:2011-10-02 新浪博客
Struts2验证比起Struts1验证框架来,好用多了,使程序更加清晰易读,充分利用了配置文件的作用,也 算是解耦的表现吧.
核心代码如下:
1.用户注册页面register.jsp
< ?xml:namespace prefix = s />< s:fielderror>< /s:fielderror>
< /FONT>
< !-- 读取显示提示信息 -->
< TABLE>
用户名:
密码:
< INPUT type=password name=user.password>
确认密码:
< INPUT type=password name=user.rePassword>
年龄:
< INPUT name=user.age>
生日:
< INPUT name=user.birthday>
2.注册成功欢迎页面welcome.jsp
congratulations!${user.userName}
浅谈Struts2验证框架及用户注册(2)
时间:2011-10-02 新浪博客
3.注册处理action RegisterAction
package org.kingtoon.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.kingtoon.bean.User;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport {
private User user;
@Override
public String execute() throws Exception {
if(!(user.getPassword().equals(user.getRePassword()))) {
this.addFieldError("password", "请输入相同的密码");
return "input";
}
else
{
HttpServletRequest request = ServletActionContext.getRequest ();
request.setAttribute("user", user);
return SUCCESS;
}
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
4. 用户Bean User.java
package org.kingtoon.bean;
import java.util.Date;
public class User {
private String userName;
private String password;
private String rePassword;
private Integer age;
private Date birthday;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRePassword() {
return rePassword;
}
public void setRePassword(String rePassword) {
this.rePassword = rePassword;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
浅谈Struts2验证框架及用户注册(3)
时间:2011-10-02 新浪博客
5.配置验证文件RegisterAction-validation.xml
< VALIDATORS>
< !-- 验证字符串不能为空 -->
< FIELD- VALIDATOR type="requiredstring">
< !-- 去空格 -->
< PARAM name="trim">true
< !-- 错误提示信息 -->
< MESSAGE>用户名不能为空
< /FIELD-VALIDATOR>
< !-- 验证字符串长度 -->
< FIELD-VALIDATOR type="stringlength">
< PARAM name="minLength">2< /PARAM>
20
< MESSAGE>用户名长度应在2到18个字符间
< FIELD
|