这里使用的简单验证是Struts2中最简单的验证.
但是不得不说,struts2的验证系统还是没有JSF的好用.
首先是struts.xml文件配置
<package name="default" namespace="/" extends="struts-default"> <!-- action name is Visit URL's path,you can write 'hello.jsp' or 'hello' or 'hello.action' --> <!-- <action name="hello"> result不写name,其实name就是 name="success" <result> /hello.jsp </result> </action> --> <!-- 如果不写class,默认执行的是Action所要继承的类:ActionSupport --> <action name="index" class="org.credo.action.IndexAction"> <!-- result不写name,其实name就是 name="success" --> <result> /index.jsp </result> <result name="error"> /userinfo/success.jsp </result> </action> </package>
其次是action的配置.
package org.credo.action; import com.opensymphony.xwork2.ActionSupport; public class IndexAction extends ActionSupport{ /** * 企业开发一般都必须使用继承ActionSupport接口来做. */ private static final long serialVersionUID = 1L; private String name; public String execute(){ System.out.println("name:"+name); if(name == null || !name.trim().equals("admin")){ this.addFieldError("name", "name is error"); this.addFieldError("name", "name is too long"); this.addFieldError("name2", "name is too long"); return ERROR; } return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
接着就是UI页面:
<form action="index" method="post"> 姓名:<input type="text" name="name"></input> <input type="submit" value="submit" /> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'MyJsp.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <s:text name="success">Success</s:text> <s:fielderror fieldName="name" theme="simple"/><br/> 123,filedName等于this.addFieldError("name", "name is error");中的"name",样式默认就为"simple"<br/> <br/> <s:property value="errors" /><br/> <s:property value="errors.name[1]"/> //errors是map,name是数组,so.... <br/> //下面是struts ValueStack debug,s:property可以通过NAME获取值. <s:debug></s:debug> </body> </html>
这里使用了2个struts2的标签.一个是<s:filedName>一个是<s:property>
第一个的说明很完全了.而第二个对应的是<s:debug>中的errors(是一个map)的value(是一个数组).filedName同理.
这里就是后台你手动传入的参数.
所有的struts2的验证,这个是最基本的,也是最常用的一个.