首先是STRUTS.XML的配置。重点在于配置文件:
<!-- struts2捕获action类异常 -->
<global-results>
<result name="error">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
这样一块。
<?xml version="1.0" encoding="UTF-8" ?
><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 採用注解的方式 --> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="" extends="struts-default"> <!-- struts2捕获action类异常 --> <global-results> <result name="error">/error.jsp</result> </global-results> <global-exception-mappings> <exception-mapping result="error" exception="java.lang.Exception"></exception-mapping> </global-exception-mappings> <action name="link" class="com.test.action.LoginAction"> <result>/result.jsp</result> </action> <action name="linkIOC" class="com.test.action.LoginActionIOC"> <result>/result.jsp</result> </action> </package> <!-- Add packages here --> </struts>
測试类
package com.test.action;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private Map request;
private Map session;
private Map application;
public LoginAction()
{
System.out.println("loginaction构造函数!");
request=(Map) ActionContext.getContext().get("request");
session=ActionContext.getContext().getSession();
application=ActionContext.getContext().getApplication();
}
public String execute()
{
//System.out.println(request);
//System.out.println(session);
//System.out.println(application);
int i=100/0;/*这个地方会抛出异常,默认情况下struts2是不会捕获异常,直接抛出*/
request.put("msg", "欢迎你!");
return SUCCESS;
}
}
输出结果