Struts简单数据验证
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts><constant name="struts.devMode" value="true" /> <package name="validate" namespace="/" extends="struts-default"><action name="*-*" method="{2}"><result name="success" type="dispatcher">/{1}-{2}.jsp</result><result name="error" >/error.jsp</result></action></package></struts>
?
package com.wepull.action;import java.util.Date;import com.opensymphony.xwork2.ActionSupport;public class ValidateAction extends ActionSupport{private String name;@Overridepublic String execute() throws Exception {System.out.println(name);if(name==null||"admin".equalsIgnoreCase(name)){this.addFieldError("errorName", "名字为空或不不合法");return ERROR;}return SUCCESS;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
?Validate-execute.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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 'index.jsp' starting page</title> </head> <body> 可以注册用户名:${name } </body></html>
?error.jsp
<%@ 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 'index.jsp' starting page</title> </head> <body> <s:fielderror name="errorName"></s:fielderror> <br> <br> <s:property value="errors.errorName"/> <br> <s:property value="errors.errorName[0]"/> <s:debug></s:debug> </body></html>
?