简单的数据验证:使用addFieldError方法和s:fieldError标签简单处理数据校验(一般不使用)
1.编写index.jsp
<?xml version="1.0" encoding="GB18030" ?> <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030" /> <base href="<%=basePath %>"/> <title>Insert title here</title> </head> <body> 使用addFieldError方法和s:fieldError标签简单处理数据校验 <a href="user/user!add?name=a" >添加用户</a> </body> </html>
2.编写action
package com.bjsxt.struts2.user.action; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { private String name; public String add() { //对name属性进行校验 if(name == null || !name.equals("admin")) { this.addFieldError("name", "name is error");//调用addFieldError方法,将提示信息存放到value stack contents中 this.addFieldError("name", "name is too long");//查看值栈中的内容,可以同一个name可以对应多个值 return ERROR; } return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3.struts.xml配置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="user" extends="struts-default" namespace="/user"> <action name="user" class="com.bjsxt.struts2.user.action.UserAction"> <result name="error">/error.jsp</result> </action> </package> </struts>
4.编写error.jsp,使用struts的标签获取错误信息
<?xml version="1.0" encoding="GB18030" ?> <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@taglib uri="/struts-tags" prefix="s" %><!--使用struts2的标签--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030" /> <title>Insert title here</title> </head> <body> User Add Error! <!--提示信息会有默认的样式,不实用。可以从浏览器中查看源码--> <s:fielderror fieldName="name" theme="simple"/><!--获取value stack contents的数据--> <br /> <s:property value="errors.name[0]"/><!--使用OGNL表达式获取value stack contents中的内容--> <s:debug></s:debug><!--使用这个标签可以查看value stack contents中的数据--> </body> </html>