如何处理Struts中的异常?

时间:2011-11-23 11:15:05

标签: java-ee exception-handling struts struts-1

我是Struts的新手,目前正在研究它的1.3.8版本。请给我一个在struts-confg.xml文件中使用处理异常的简单示例。

由于

1 个答案:

答案 0 :(得分:1)

PLS。检查http://livingtao.blogspot.com/2007/05/global-exception-handling-for-struts.html此链接或

新解决方案

我完全放弃了struts-config中的全局异常方法,并在web.xml文件中添加了一个部分,指示应用服务器将请求转发到所有未处理异常的指定URL。

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error</location>
</error-page>

然后将一个servlet和一个servlet映射添加到/ error URL

<servlet> 
<servlet-name>exceptionHandler</servlet-name> 
<servlet-class>com.test.ExceptionHandlerServlet</servlet-class> 
<init-param> 
<param-name>errorPageURL</param-name> 
<param-value>error.html</param-value> 
</init-param> 
<load-on-startup>3</load-on-startup> 
</servlet>


<servlet-mapping>
<servlet-name>exceptionHandler</servlet-name> 
<url-pattern>/error</url-pattern> 
 </servlet-mapping>

ExceptionHandlerServlet将记录异常并将浏览器重定向到servlet配置中定义的URL(error.html)。

ExceptionHandlerServlet代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
logger.debug("Handling exception in ErrorHandlerServlet");

Throwable exception = null;

// Check if struts has placed an exception object in request
Object obj = request.getAttribute(Globals.EXCEPTION_KEY);

if (obj == null) {
// Since no struts exception is found,
// check if a JSP exception is available in request.
obj = request.getAttribute("javax.servlet.jsp.jspException");
}

if ((obj != null) && (obj instanceof Throwable)) {
exception = (Throwable) obj;
}

if (logger.isDebugEnabled()) {
logger.debug("Request URI: " + request.getAttribute("javax.servlet.forward.request_uri"));
}

// request uri containing the original URL value will be available
// only on servers implementing servlet 2.4 spec
String requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");

logger.error("Exception while handling request: " + requestURI, exception);
response.sendRedirect(errorPageURL);
} catch (Exception e) {
// Throwing exceptions from this method can result in request
// going in to an infinite loop forwarding to the error servlet recursively.
e.printStackTrace();
}
}

现在,在所有未处理的异常上,servlet将记录异常。然而,在其中一个tile JSP中抛出异常的某些情况下,浏览器会显示部分呈现的页面,并且不会重定向到错误页面。

这是因为在呈现整个页面之前将内容刷新到响应缓冲区。在这种情况下,浏览器会很乐意显示收到的内容,重定向到错误页面将无效。

为了防止或最小化响应缓冲区的刷新:

  1. 在所有切片标签中将flush属性设置为false
  2. 增加响应缓冲区大小以最小化自动刷新
  3. 这是通过修改tile布局jsp页面来实现的。

    <!-- sets the response buffer size to 64kb -->
    <%@ page buffer="64kb"%>
    <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles"%>
    …
    <tiles:insert attribute="header" flush="false" />
    <tiles:insert attribute="leftnav" flush="false" />
    <tiles:insert attribute="body" flush="false" />
    <tiles:insert attribute="footer" flush="false" />
    

    在上面的代码段中,为清晰起见,删除了所有html格式。响应缓冲区设置为64千字节,此值应根据应用程序的平均页面大小和增加的内存使用量对性能的影响来决定。