声明式验证

如果action的名字是UserController,在UserController所在包目录下添加
UserController-validation.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
 <field name="loginName">
  <field-validator type="requiredstring">
   <message>请输入邮箱地址</message>
  </field-validator>
  <field-validator type="email">
   <message>邮箱格式不正确</message>
  </field-validator>
 </field>

 <field name="name">
  <field-validator type="requiredstring">
   <message>请输入姓名</message>
  </field-validator>
  <field-validator type="stringlength">
   <param name="minLength">6</param>
   <param name="maxLength">20</param>
   <message>姓名长度只能在 ${minLength} 和 ${maxLength} 之间.</message>
  </field-validator>
 </field>

 <field name="password">
  <field-validator type="requiredstring">
   <message>请输入密码</message>
  </field-validator>
  <field-validator type="stringlength">
   <param name="minLength">6</param>
   <param name="maxLength">12</param>
   <message>密码长度只能在 ${minLength} 和 ${maxLength} 之间.</message>
  </field-validator>
 </field>
</validators>


ACTION中不需要验证的方法前加上
@SkipValidation

在页面中使用<s:fielderror/>显示错误信息
验证用户输入有误的话 默认转向input视图

JSP中不用标签可以用如下方式取到fielderror的值
<%@ page import="com.opensymphony.xwork2.*"%>
<%@ page import="com.opensymphony.xwork2.util.*"%>
<%@ page import="java.util.*"%>
<%
       ActionContext cxt = ActionContext.getContext();
       out.println("<h2>ValueStack</h2>");
       ValueStack stack = cxt.getValueStack();
       Object uc = stack.findValue("[1].fieldErrors.loginName");
       out.print(uc);
       List list = (List) stack.getRoot();
       for (int i = 0; i < list.size(); i++) {
        out.print("<FONT Color='Red'>" + list.get(i) + "</FONT>");
        out.println("<BR/>");
       }
%>


stack.findValue("[1].fieldErrors.loginName");
ValueStack stack是个LIST 取得第一个元素的fieldErrors属性的,
fieldErrors是个MAP 的KEY为loginName的值

你可能感兴趣的:(jsp,xml)