Use Java filter to implement service exception interception and jump to the error message page

Source: Internet
Author: User

1. Reason: we will certainly encounter custom business exceptions during the project, and then jump the business exception information to the unified information prompt page, for example, when we use struts, we will use the Exception Handling Mechanism of Struts. when we run out of the business layer, we will encounter a service exception, and then submit it to struts to display the prompt information on a page, to remind users of related operations. Here we will design how to display this function based on the above scenarios.

2. Solution: Our Business exceptions are usually thrown, namely, the unchecked exception, so it will always arrive at the outermost layer that calls this method for capture, generally, we call our business methods in action, and the business methods may run out of exceptions. Now we can make some articles at this time. We can use filter, to capture the exception we throw, and then jump to a unified page for information prompts.

3. Specific Code:

① Custom exception class. I don't need to talk about this. Everyone will:

Bsexception. Java

Package COM. ajun. exception;/*** business exception class * @ author ajun * @ http://blog.csdn.net/ajun_studio */public class bsexception extends runtimeexception {// Exception Code private string key; private object [] values; // some other information: Public bsexception () {super ();} public bsexception (string message, throwable) {super (message, throwable);} public bsexception (string message) {super (Message);} public bsexception (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 ;}}

Now that you want to use filter, You can naturally implement the filter interface to intercept the request you want, and then you can capture exceptions. At this time, you can perform operations on your chain. dofilter performs try catch and then judges the exception you want to catch. It is very simple. Please refer to the Code:

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;/*** service exception filter * @ 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; // capture the industry you throw Please {chain. dofilter (req, Res);} catch (runtimeexception e) {If (E instanceof bsexception) {// if the request is a business exception you have defined. setattribute ("bsexception", e); // a request for storing business exception information. getrequestdispatcher (errorpage ). forward (request, response); // jump to the Information prompt page !!} E. printstacktrace () ;}}// initialize to read the prompt page path of your configuration public void Init (filterconfig config) throws servletexception {// read the error message prompt page path errorpage = config. getinitparameter ("errorpage"); If (null = errorpage | "". equals (errorpage) {Throw new runtimeexception ("no error message is configured to jump to the page. Please try again on the web. configure \ n <init-param> \ n <param-Name> errorpage </param-Name> \ n <param-value>/error in XML. JSP </param-value> \ n </init-param> \ n path can be any valid path page set by yourself !! "); // System. Out. println (" no error message is configured to jump to the page ");}}}

The filter configuration in Web. XML is as follows:

<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>

Let's write a Servlet and throw a defined business exception during the request to test it.

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 (); // simulate calling the business layer method. An exception is thrown in this method, which is captured in the filter .}}

Configure the servlet in Web. xml

  <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>

Service class called in servlet during testing

Testservice. Java

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 !! "); // Throw an exception according to your business logic }}}

To deploy the project now, enter http: // localhost: 8080/bsexception/ajun. do in your browser.

Jump to error. jsp: Display: In add () throws Exception !!

Obtain the following information in the background:

add () was called!!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.java:17)......

Succeeded. Please implement it now...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.