在ActionForm中重写父类的方法validate(),该方法会在参数传递过来后对属性的进行验证,验证不同过的时候,会根据struts-config.xml文件中的Action配置返回到input属性所指定的界面,可以使用<bean:message property=””>从request范围中取出对应的错误信息提示用户
在ActionForm中验证
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
public class HelloForm extends ActionForm {
private static final long serialVersionUID = 1L;
private String userName = null;
public String getUserName() {
return (this.userName);
}
public void setUserName(String userName) {
this.userName = userName;
}
/**
* 把属性重新设置为默认值
* Reset all properties to their default values.
*/
@Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.userName = null;
}
/**
* 用于表单验证
*/
@Override
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {
// // 创建一个ActionMessage来存放错误信息
// ActionMessages actionMessages=new ActionMessages();
// /*
// * 向ActionMessage存放信息
// * property:为ActionMessage对象的key
// * ActionMessage中key为资源文件中的key,Object为向资源文件传递的第一个参数{0}
// */
// actionMessages.add("property",new ActionMessage("key",new Object()));
ActionErrors errors = new ActionErrors();
if ((userName == null) || (userName.length() < 1)){
errors.add("username", new ActionMessage("hello.no.username.error"));
}
return errors;
}
}
在Action中验证
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import com.cong.helloapp.Constants;
import com.cong.helloapp.bean.HelloForm;
import com.cong.helloapp.bean.PersonBean;
public class HelloAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
// 在MessageRecourse对象中封装了对本地化的资源文件,过去要获取properties文件中的key,可以使用getMassage来获取
MessageResources messages = getResources(request);
messages.getMessage("hello.jsp.title");
/*
* 创建一个ActionMessages对象,如果userName对象为空的话,则向其中添加<String,new ActionMessage>
* 键值对的错误信息,并转发到响应的页面
*/
ActionMessages errors = new ActionMessages();
String userName = (String)((HelloForm) form).getUserName();
String badUserName = "Monster";
if (userName.equalsIgnoreCase(badUserName)) {
/*
* new ActionMessage(String key, Object value0)
* key:表示资源文件中的key值
* value0:匹配资源文件中的第一个参数,eg:{0}
*/
errors.add("username", new ActionMessage("hello.dont.talk.to.monster", badUserName));
/*
* 将错误信息添加到request中
*/
saveErrors(request, errors);
/*
* 返回Action中的input对应的jsp页面
*/
return (new ActionForward(mapping.getInput()));
}
PersonBean pb = new PersonBean();
pb.setUserName(userName);
pb.saveToPersistentStore();
// 将PersonBean对象存放到request作用于中,通过request传递到jsp页面中
request.setAttribute( Constants.PERSON_KEY, pb);
// 由于在上面的代码中,将PersonBean的数据添加到了request中,所以不需要将PersonBean转发到jsp页面,所以可取消mapping的传递
request.removeAttribute(mapping.getAttribute());
// Forward control to the specified success URI
return (mapping.findForward("SayHello"));
}
}
struts-config.xml文件配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<!-- This is the Struts configuration file for the "Hello!" sample application -->
<struts-config>
<!-- ======== Form Bean Definitions =================================== -->
<form-beans>
<form-bean name="HelloForm" type="com.cong.helloapp.bean.HelloForm" />
</form-beans>
<!-- ========== Action Mapping Definitions ============================== -->
<action-mappings>
<!-- Say Hello! -->
<!--
path:指定该请求的访问路径
type:该请求所处理的Action
name:指定传递给Action的ActionForm Bean
validate:进入bean文件时是否进行验证
input:当验证失败后返回的input界面
-->
<action path="/HelloWorld" type="com.cong.helloapp.action.HelloAction"
name="HelloForm" scope="request" validate="true" input="/hello.jsp">
<forward name="SayHello" path="/WEB-INF/jsp/hello.jsp" />
</action>
</action-mappings>
<!-- ========== Message Resources Definitions =========================== -->
<message-resources parameter="com.cong.helloapp.resources.application" />
</struts-config>
web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <display-name>HelloApp Struts Application</display-name> <!-- Standard Action Servlet Configuration --> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <!-- Standard Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>hello.jsp</welcome-file> </welcome-file-list> <!-- Struts Tag Library Descriptors --> <taglib> <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib> <taglib> <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> <taglib> <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri> <taglib-location>/WEB-INF/struts-logic.tld</taglib-location> </taglib> </web-app>
hello.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<html:html lang="true">
<head>
<title><bean:message key="hello.jsp.title" /></title>
<html:base/>
</head>
<body bgcolor="white">
<p>
<h2><bean:message key="hello.jsp.page.heading" /></h2>
<p>
<!-- 显示指定的错误信息 -->
<html:errors property="username" />1111<br>
<html:errors property="a" />
---
<!--
通过html:message来显示错误信息
name:指定ActionMessage对象存放在request或者session范围内的属性key
message:指定消息的来源,如果为true,则从request或者session中取出ActionErrors.GLOBAL_MESSAGE的ActionMessage对象
id:对取出来的ActionMessage对象进行命名
-->
<html:messages id="error" message="false" >
<bean:write name="error" /><br>
</html:messages>
<!-- 显示错误信息(全部显示) -->
<html:errors/>
<p>
<logic:present name="personbean" scope="request">
<h2>
<bean:message key="hello.jsp.page.hello" />
<bean:write name="personbean" property="userName" />
</h2>
</logic:present>
<html:form action="/HelloWorld.do" focus="userName">
<bean:message key="hello.jsp.prompt.person" />
<html:text property="userName" size="16" maxlength="16" /><br>
<html:submit />
<html:reset />
</html:form><br>
<html:img page="/stauts-power.gif" alt="Powered By Struts"/>
</body>
</html:html>