日期:2014-05-18  浏览次数:20658 次

struts2数据验证问题
代码如下
login.jsp
<body>
 <s:i18n name="properties/messageResource">
       <s:text name="today is"/>
  <% java.util.Date now=new java.util.Date();
  pageContext.setAttribute("now",now); %>
  <s:date name="#attr.now" format="yyyy/MM/dd" nice="false"/>
  <hr>
  <s:form action="usrLoginAction.action" method="post">
   <h2><s:text name="loginTip"/></h2>
   <br/>
   <h4><s:textfield name="username" key="user"/></h4>
   <br/>
   <h4><s:password name="password" key="password"/></h4>
   <br/>
    <s:submit name="submit" key="submit"/>
    <br/>
    
   </s:form>
</s:i18n>
  </body>
UsrLoginAction.java
package com.ascent.action;
import java.util.ArrayList;
import com.ascent.anli.Usr;
import com.ascent.anli.UsrDAO;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UsrLoginAction extends ActionSupport{
private String username;
private String password;
private String tip;
private ArrayList dataList;
@SuppressWarnings("rawtypes")
public ArrayList getDataList()
{
return dataList;
}
public void setDataList(ArrayList dataList)
{
this.dataList=dataList;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password=password;
}
public String getTip(){
return tip;
}
public void setTip(String tip){ 
this.tip=tip;
}
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username=username;
}
public void validate() {
//如果用户名为null,或者为空的话,那么提示错误信息
if(getUsername() == null || "".equals(getUsername().trim())){
this.addFieldError("username", this.getText("username.required"));
}

//如果密码为null,或者为空的话,那么提示错误信息
if(getPassword() == null || "".equals(getPassword().trim())){
this.addFieldError("password", this.getText("password.required"));
}
}
public String execute()throws Exception{
UsrDAO dao=new UsrDAO();
Usr u=dao.checkUsr(username, password);
if(u==null){
return "error";
}
else{
ActionContext.getContext().getSession().put("usr", u);
String superuser=u.getSuperuser();
if(superuser.equals("1")){
return "success1";
}else if(superuser.equals("2")){
return "success2";
}
else return "success3";
}
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"