The NoteBook of EricKong

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  611 Posts :: 1 Stories :: 190 Comments :: 0 Trackbacks

1、缘由:我们在做项目中肯定都会遇到自定义业务异常 ,然后将业务异常信息跳转的统一的信息提示页面的情况,比如我们在struts的时候我们会用到struts的异常处理机制,我们在业务层会跑出我们遇到业务处理异常 ,然后交由struts处理将提示信息到一个页面进行显示,来提示用户的相关操作,这里我们会根据以上情景设计一下怎么来显示该功能。

2、解决方法:我们的业务异常通常都是抛出的,就是unchecked exception,所以最后总会到达调用该方法的最外层进行捕获,一般我们都会在action中调用我们的业务方法 ,而业务方法可能会跑出异常,此时我们就可以在此时做些文章了, 我们可以利用filter,来捕获我们抛出的异常,然后跳转到一个统一页面,进行信息提示了。

3、具体代码:

①自定义异常类,我想这个就不用多说了 ,大家都是会的:

BsException.java

 

 package com.ajun.exception; 
 
 
/**
 * 业务异常类
 * @author ajun
 * @http://blog.csdn.net/ajun_studio
 */ 
public class BsException extends RuntimeException { 
 
    //异常代码  
    private String key; 
     
    private Object[] values;//一些其他信息  
     
    public BsException() { 
        super(); 
    } 
 
    public BsException(String message, Throwable throwable) { 
        super(message, throwable); 
    } 
 
    public BsException(String message) { 
        super(message); 
    } 
 
    public BsException(Throwable throwable) { 
        super(throwable); 
    } 
     
    public BsException(String message,String key){ 
        super(message); 
        this.key = key; 
    } 
     
    public BsException(String message,String key,Object value){ 
        super(message); 
        this.key = key; 
        this.values = new Object[]{value}; 
    } 
     
    public BsException(String message,String key,Object[] values){ 
        super(message); 
        this.key = key; 
        this.values = values; 
    } 
 
    public String getKey() { 
        return key; 
    } 
 
    public Object[] getValues() { 
        return values; 
    } 

package com.ajun.exception;


/**
 * 业务异常类
 * @author ajun
 * @http://blog.csdn.net/ajun_studio
 */
public class BsException extends RuntimeException {

 //异常代码
 private String key;
 
 private Object[] values;//一些其他信息
 
 public BsException() {
  super();
 }

 public BsException(String message, Throwable throwable) {
  super(message, throwable);
 }

 public BsException(String message) {
  super(message);
 }

 public BsException(Throwable throwable) {
  super(throwable);
 }
 
 public BsException(String message,String key){
  super(message);
  this.key = key;
 }
 
 public BsException(String message,String key,Object value){
  super(message);
  this.key = key;
  this.values = new Object[]{value};
 }
 
 public BsException(String message,String key,Object[] values){
  super(message);
  this.key = key;
  this.values = values;
 }

 public String getKey() {
  return key;
 }

 public Object[] getValues() {
  return values;
 }
}
既然要用到filter ,自然少不了实现Filter接口,拦截你想要的请求,然后,就可以捕获异常了,此时你可以对你的chain.doFilter进行try catch,然后判断你想捕获的异常,很简单 ,请看代码:


 package com.ajun.filter; 
 
import java.io.IOException; 
 
import javax.servlet.Filter; 
import javax.servlet.FilterChain; 
import javax.servlet.FilterConfig; 
import javax.servlet.ServletException; 
import javax.servlet.ServletRequest; 
import javax.servlet.ServletResponse; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import com.ajun.exception.BsException; 
 
/**
 * 业务异常过滤器
 * @author ajun
 * @http://blog.csdn.net/ajun_studio
 */ 
public class ExceptionFiler implements Filter { 
 
    private String errorPage;//跳转的错误信息页面  
     
     
    public void destroy() { 
         
    } 
 
    public void doFilter(ServletRequest req, ServletResponse res, 
            FilterChain chain) throws IOException, ServletException { 
 
         HttpServletResponse response = (HttpServletResponse) res; 
         HttpServletRequest request = (HttpServletRequest) req; 
         //捕获你抛出的业务异常  
         try { 
            chain.doFilter(req, res); 
        } catch (RuntimeException e) { 
            if(e instanceof BsException){//如果是你定义的业务异常  
                request.setAttribute("BsException", e);//存储业务异常信息类  
                request.getRequestDispatcher(errorPage).forward(request, response);//跳转到信息提示页面!!  
            } 
            e.printStackTrace(); 
        } 
    } 
       //初始化读取你配置的提示页面路径  
    public void init(FilterConfig config) throws ServletException { 
        //读取错误信息提示页面路径  
        errorPage = config.getInitParameter("errorPage"); 
        if(null==errorPage || "".equals(errorPage)){ 
            throw new RuntimeException("没有配置错误信息跳转页面,请再web.xml中进行配置\n<init-param>\n<param-name>errorPage</param-name>\n<param-value>/error.jsp</param-value>\n </init-param>\n路径可以是你自己设定的任何有效路径页面!!"); 
            //System.out.println("没有配置错误信息跳转页面");  
        } 
    } 
 

package com.ajun.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ajun.exception.BsException;

/**
 * 业务异常过滤器
 * @author ajun
 * @http://blog.csdn.net/ajun_studio
 */
public class ExceptionFiler implements Filter {

 private String errorPage;//跳转的错误信息页面
 
 
 public void destroy() {
  
 }

 public void doFilter(ServletRequest req, ServletResponse res,
   FilterChain chain) throws IOException, ServletException {

   HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      //捕获你抛出的业务异常
      try {
   chain.doFilter(req, res);
  } catch (RuntimeException e) {
   if(e instanceof BsException){//如果是你定义的业务异常
    request.setAttribute("BsException", e);//存储业务异常信息类
    request.getRequestDispatcher(errorPage).forward(request, response);//跳转到信息提示页面!!
   }
   e.printStackTrace();
  }
 }
       //初始化读取你配置的提示页面路径
 public void init(FilterConfig config) throws ServletException {
  //读取错误信息提示页面路径
  errorPage = config.getInitParameter("errorPage");
  if(null==errorPage || "".equals(errorPage)){
   throw new RuntimeException("没有配置错误信息跳转页面,请再web.xml中进行配置\n<init-param>\n<param-name>errorPage</param-name>\n<param-value>/error.jsp</param-value>\n </init-param>\n路径可以是你自己设定的任何有效路径页面!!");
   //System.out.println("没有配置错误信息跳转页面");
  }
 }

}

Filter在web.xml中的配置如下:


view plaincopy to clipboardprint?
<filter> 
    <filter-name>ExceptionFilter</filter-name> 
    <filter-class>com.ajun.filter.ExceptionFiler</filter-class> 
    <init-param> 
        <param-name>errorPage</param-name> 
        <param-value>/error.jsp</param-value> 
    </init-param> 
</filter> 
<filter-mapping> 
    <filter-name>ExceptionFilter</filter-name> 
    <url-pattern>*.do</url-pattern> 
</filter-mapping> 
 <filter>
  <filter-name>ExceptionFilter</filter-name>
  <filter-class>com.ajun.filter.ExceptionFiler</filter-class>
  <init-param>
      <param-name>errorPage</param-name>
      <param-value>/error.jsp</param-value>
     </init-param>
 </filter>
 <filter-mapping>
  <filter-name>ExceptionFilter</filter-name>
  <url-pattern>*.do</url-pattern>
 </filter-mapping>
下面写个servlet ,在请求的时候抛出你定义业务异常来试验一下吧


 package com.ajun.servlet; 
 
import java.io.IOException; 
import java.io.PrintWriter; 
 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
public class ExServlet extends HttpServlet { 
 
     
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
 
        this.doPost(request, response); 
         
    } 
 
     
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
 
        TestService t = new TestService(); 
        t.add();//模拟调用业务层方法,在此方法内抛出异常,此异常会在filter中进行捕获。  
         
    } 
 

package com.ajun.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ExServlet extends HttpServlet {

 
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  this.doPost(request, response);
  
 }

 
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  TestService t = new TestService();
  t.add();//模拟调用业务层方法,在此方法内抛出异常,此异常会在filter中进行捕获。
  
 }

}
web.xml配置上述servlet


view plaincopy to clipboardprint?
<servlet> 
  <servlet-name>ExServlet</servlet-name> 
  <servlet-class>com.ajun.servlet.ExServlet</servlet-class> 
</servlet> 
 
<servlet-mapping> 
  <servlet-name>ExServlet</servlet-name> 
  <url-pattern>*.do</url-pattern> 
</servlet-mapping> 
  <servlet>
    <servlet-name>ExServlet</servlet-name>
    <servlet-class>com.ajun.servlet.ExServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>ExServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
测试时在servlet中被调用的业务类

TestService.java


view plaincopy to clipboardprint?
package com.ajun.servlet; 
 
import com.ajun.exception.BsException; 
 
public class TestService { 
 
    public void add(){ 
         
        System.out.println("add () was called!!"); 
        if(true){ 
            throw new BsException("in add() throws exception!!");//抛出异常,根据你的业务逻辑  
        } 
    } 

package com.ajun.servlet;

import com.ajun.exception.BsException;

public class TestService {

 public void add(){
  
  System.out.println("add () was called!!");
  if(true){
   throw new BsException("in add() throws exception!!");//抛出异常,根据你的业务逻辑
  }
 }
}

现在部署项目,在你的浏览器内输入:http://localhost:8080/BsException/ajun.do

成功跳转到error.jsp:显示:in add() throws exception!!

在后台得到:


 com.ajun.exception.BsException: in add() throws exception!! 
    at com.ajun.servlet.TestService.add(TestService.java:11) 
    at com.ajun.servlet.ExServlet.doPost(ExServlet.java:26) 
    at com.ajun.servlet.ExServlet.doGet(ExServlet

posted on 2011-12-29 18:20 Eric_jiang 阅读(4773) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: