---
title: "避免用户看到异常 "
author: "wgcode"
date: "2010-11-12T19:16:47Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-11-12T19:16:47Z"
id: 810182
url: "https://tts.iteye.com/blog/810182"
---

尽管Struts框架提供了有效的异常处理机制，但不能保证处理所有的错误，这时Struts框架会把错误抛给Web容器，在默认情况下Web容器会向用户浏览器直接返回原始信息。如果想避免直接让用户看到这些原始信息，可以在web.xml中配置&lt;error-page&gt;元素，以下代码演示了如何避免用户看到HTTP 404、HTTP 500错误和Exception异常。

web.xml

Java代码[](http://neil-jh.iteye.com/blog/199711 "复制代码")

01. &lt;error-page&gt;
02. &lt;error-code&gt;404&lt;/error-code&gt;
03. &lt;location&gt;/exception/error404.jsp&lt;/location&gt;
04. &lt;/error-page&gt;
05. &lt;error-page&gt;
06. &lt;error-code&gt;500&lt;/error-code&gt;
07. &lt;location&gt;/exception/error500.jsp&lt;/location&gt;
08. &lt;/error-page&gt;
09. &lt;error-page&gt;
10. &lt;exception-type&gt;java.lang.Exception&lt;/exception-type&gt;
11. &lt;location&gt;/exception/default.jsp&lt;/location&gt;
12. &lt;/error-page&gt;

```
<error-page>
    <error-code>404</error-code>
    <location>/exception/error404.jsp</location>
 </error-page>
 <error-page>
    <error-code>500</error-code>
    <location>/exception/error500.jsp</location>
 </error-page>
 <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/exception/default.jsp</location>
 </error-page>
```

 

当

WEB容器捕获到exception-type或error-code指定的错误时将跳到由location指定的页面。

问题：当form bean 为动态bean时，在action中无法对form bean数据进行验证，因为formbean没有具体实现类。action中无法引用 ActionError/ActionErrors/ActionMessage/ActionMessages:  
有时候你需要向用户提供相关处理信息，包括表单验证时发现错误等。  
1\. 相关类介绍：

```
ActionMessage：用于保存一个与资源束对应的提示信息。主要构造函数如： 
ActionMessage(String message)； 
ActionMessage(String message,paramater)。 
```

 

ActionMessages:用于保存多个ActionMessage。并在html:errors 和html:messages中起作用。  
主要构造函数：  
ActionMessages().  
主要方法是add(String property,ActionMessage message)  
ActionMessages 有一个HashMap类型messages保存多个ActionMessage对象，每个ActionMessage对象都有唯一的一个property 标识。这个property可以是自定义的任意字符串，也可以由 org.apache.struts.action.ActionMessages.GLOBAL\_MESSAGE指定  
html:messages/html:errors使用property属性访问某个资源

ActionErrors：用于保存一个与资源束对应的错误信息。用法跟ActionMessages差不多。  
ActionError不赞成使用。

2\. 版本：  
struts1.1中用ActionErrors报告错误，用ActionMessages提供信息。  
在struts1.2中使用ActionMessages提供信息和错误，不赞成使用ActionError  
struts1.3中已经没有ActionError类了。

3． AtionErrors和ActionMessages的区别

1． ActionErrors是ActionMessages的一个子类，功能几乎相同，不同点在于标签&lt;html:errors/&gt;和&lt;html:messages&gt;的使用上的区别。  
html: errors指定了footer和header属性。默认值为errors.header和errors.footer,需要时可以自己指定。如果资源属性文件配置了 errors.header和errors.footer，则任何时候使用html:errors时开头和结尾都是这两个属性对应的资源信息。  
而html:message默认情况下没有errors.header和errors.footer值，当然可以自己指定。

2． html:errors可以根据property属性指定显示一个错误信息。html:messages有一个必添项id。html:messages不能直接显示信息，它将选出的信息放入一个用id标识的Iterator对象里，然后在用ben:write或JSTL c:out标签显示每个信息.例如：

Java代码[](http://neil-jh.iteye.com/blog/199711 "复制代码")

1. &lt;html:messages message="true" id="msg"&gt;
2. &lt;c:out value="${msg}"/&gt;&lt;br /&gt;
3. &lt;/html:messages&gt;

```
<html:messages message="true" id="msg">
    <c:out value="${msg}"/><br />
</html:messages>
```

 

3\. 具体的一个例子：  
接受输入页面input.jsp:

Java代码[](http://neil-jh.iteye.com/blog/199711 "复制代码")

1. &lt;html:form action="/errormessage/input"&gt;
2. phoneNumber : &lt;html:text property="phoneNumber"/&gt; &lt;html:errors     property="&lt;%=org.apache.struts.action.ActionMessages.GLOBAL\_MESSAGE %&gt;"/&gt;&lt;br/&gt;
3. &lt;html:submit/&gt;&lt;html:cancel/&gt;
4. &lt;/html:form&gt;

```
<html:form action="/errormessage/input">
    phoneNumber : <html:text property="phoneNumber"/> <html:errors     property="<%=org.apache.struts.action.ActionMessages.GLOBAL_MESSAGE %>"/><br/>
 <html:submit/><html:cancel/>
 </html:form>
```

 

struts-config.xml:

Java代码[](http://neil-jh.iteye.com/blog/199711 "复制代码")

01. &lt;form-beans &gt;
02. &lt;form-bean name="inputForm" type="cn.rolia.struts.form.errorexception.InputForm" /&gt;
03. &lt;/form-beans&gt;
04. &lt;action-mappings &gt;
05. &lt;action
06. attribute="inputForm"
07. input="/errormessage/input.jsp"
08. name="inputForm"
09. path="/errormessage/input"
10. scope="request"
11. type="com.yourcompany.struts.action.errormessage.InputAction"
12. validate="false"&gt;
13. &lt;forward name="success" path="/errormessage/success.jsp" /&gt;
14. &lt;/action&gt;
15. &lt;/action-mappings&gt;

```
<form-beans >
    <form-bean name="inputForm" type="cn.rolia.struts.form.errorexception.InputForm" />
 </form-beans>
 <action-mappings >
    <action
      attribute="inputForm"
      input="/errormessage/input.jsp"
      name="inputForm"
      path="/errormessage/input"
      scope="request"
      type="com.yourcompany.struts.action.errormessage.InputAction"
      validate="false">
      <forward name="success" path="/errormessage/success.jsp" />
    </action>
 </action-mappings>
```

 

InputAction.java:

Java代码[](http://neil-jh.iteye.com/blog/199711 "复制代码")

01. public ActionForward execute(ActionMapping mapping, ActionForm form,
02. HttpServletRequest request, HttpServletResponse response) {
03. cn.rolia.struts.form.errorexception.InputForm inputForm = (cn.rolia.struts.form.errorexception.InputForm) form;// TODO Auto-generated method stub
04. String phoneNumber = inputForm.getPhoneNumber();
05. if(phoneNumber.length()&lt;4){
06. ActionErrors messages = new ActionErrors();
07. messages.add(org.apache.struts.action.ActionMessages.GLOBAL\_MESSAGE,new ActionMessage("error.errormessage.input"));
08. this.saveErrors(request, messages);
09. return mapping.getInputForward();
10. }
11. return mapping.findForward("success");
12. }

```
public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) {
 cn.rolia.struts.form.errorexception.InputForm inputForm = (cn.rolia.struts.form.errorexception.InputForm) form;// TODO Auto-generated method stub
 String phoneNumber = inputForm.getPhoneNumber();
 if(phoneNumber.length()<4){
 ActionErrors messages = new ActionErrors();
    messages.add(org.apache.struts.action.ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.errormessage.input"));
    this.saveErrors(request, messages);
    return mapping.getInputForward();
 }
 
 return mapping.findForward("success");
}
```

 

解说：用户输入手机号码，页面跳转到InputAction控制层进行处理，若输入数据小于4，则创建一个ActionMessage类存储相关错误信息。然后再创建ActionErrors类将此ActionMessage放入ActionErrors。再调用Action的saveErrors方法将此ActionErrors保存的request范围里，然后返回input.jsp页面要求重新输入并用html:errors提示错误信息。

4\. Action包含saveErrors()方法和saveMessages()方法。如果创建的ActionErrors则应该调用saveErrors()，若创建的是ActionMessages则应该调用saveMessages()方法。  
saveErrors ()接收ActionMessages而不是ActionErrors;同时将其保存在request中并用一个由 org.apache.struts.Globals.ERROR\_KEY指定的常量” org.apache.struts.Globals.ERROR\_KEY”标识这个ActionMessages，便于html:errors查找。 saveMessages()方法接收ActionMessages同时将其保存在request中并用一个由 org.apache.struts.Globals.MESSAGE\_KEY指定的常量” org.apache.struts.Globals.MESSAGE\_KEY”标识这个ActionMessages，进而让html: messages从常量Globals.ERROR\_KEY中遍历获取信息。可以将其属性message设置为true，那么它将从常量 Globals.MESSAGE\_KEY中遍历获取信息。

5\. 默认情况下html:messages从  
如果你想将信息保存在session里而不是request，struts1.2提供了  
struts1.1 没有的saveMessages(HttpSession session, ActionMessages messages)方法和saveErrors(javax.servlet.http.HttpSession session, ActionMessages errors)方法。

InputAction.java:

Java代码[](http://neil-jh.iteye.com/blog/199711 "复制代码")

01. public ActionForward execute(ActionMapping mapping, ActionForm form,
02. HttpServletRequest request, HttpServletResponse response) {
03. cn.rolia.struts.form.errorexception.InputForm inputForm = (cn.rolia.struts.form.errorexception.InputForm) form;// TODO Auto-generated method stub
04. String phoneNumber = inputForm.getPhoneNumber();
05. if(phoneNumber.length()&lt;4){
06. ActionErrors messages = new ActionErrors();
07. messages.add(org.apache.struts.action.ActionMessages.GLOBAL\_MESSAGE,new ActionMessage("error.errormessage.input"));
08. this.saveErrors(request.getSession(true), messages);
09. return mapping.getInputForward();
10. }
11. return mapping.findForward("success");
12. }

```
public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) {
cn.rolia.struts.form.errorexception.InputForm inputForm = (cn.rolia.struts.form.errorexception.InputForm) form;// TODO Auto-generated method stub
 String phoneNumber = inputForm.getPhoneNumber();
 if(phoneNumber.length()<4){
    ActionErrors messages = new ActionErrors();
    messages.add(org.apache.struts.action.ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.errormessage.input"));
    this.saveErrors(request.getSession(true), messages);
    return mapping.getInputForward();
 }
 
 return mapping.findForward("success");
}
```