Struts2 简单数据验证

1、struts.xml

<struts>
 <constant name="struts.devMode" value="false" /> 
 <constant name="struts.enable.DynamicMethodInvocation" value="true" />
 <constant name="struts.i18n.encoding" value="utf-8"></constant>
 <package name="user"  extends="struts-default">                 
        <action name="user" class="com.wxh.action.UserAction" >
            <result >/useraddsuccess.jsp</result>
            <result name="error">/addError.jsp</result>
        </action>         
  </package>   
</struts>

2、UserAction.java

package com.wxh.action;
 
import com.opensymphony.xwork2.ActionSupport;

public  class UserAction extends ActionSupport{

private static final long serialVersionUID = 1L; 
		
	private String name;
	public String add(){
//逻辑判断
		if(name==null || !name.equals("admin")){
			this.addFieldError("name", "name is error");
			this.addFieldError("name", "name is too long");
			return ERROR;//返回到result的name为“ERROR”所指定的jsp页面。
		}
		return SUCCESS;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
}


3、index.jsp

<body>
使用addFieldError方法和s:fieldError标签简单处理数据校验<a href="user!add?name=小王">添加用户</a>
</body>

4、addError.jsp

<%@taglib uri="/struts-tags" prefix="s" %><!--用到ognl表达式时需要这句-->
<body>
User Add Error!
<s:fielderror fieldName="name" theme="simple"/>
<br/>
<s:property value="error.name[0]"/>
<s:debug></s:debug>
</body>




你可能感兴趣的:(struts2.0)