Unified exception Handling in "Springmvc learning 07" Springmvc

Source: Internet
Author: User
Tags getmessage

We know that the exception in the system includes: compile-time exception and run-time exception runtimeexception, the former by catching the exception to obtain the exception information, the latter mainly through the specification code development, test through means to reduce the occurrence of runtime exceptions. In the development, whether the DAO layer, service layer or controller layer, it is possible to throw an exception, in Springmvc, all types of exception processing can be decoupled from the processing process, not only to ensure that the relevant processing process of a single function, It also realizes the unified processing and maintenance of abnormal information. This blog post mainly summarizes how exceptions are handled uniformly in SPRINGMVC.

1. Exception Handling Ideas

First look at the SPRINGMVC, the idea of exception handling (I have tried to draw a good view, do not spray me ~):

As shown, the system's DAO, service, controller exceptions are thrown up through throws exception, and finally by the SPRINGMVC front-end controller to the exception handler for exception processing. SPRINGMVC provides a global exception handler (a system with only one exception handler) for uniform exception handling. Understanding the exception handling mechanism in SPRINGMVC, we begin to analyze the exception handling in SPRINGMVC.

2. Simple exception handler in Springmvc

SPRINGMVC has an exception handler called Simplemappingexceptionresolver, the processor implements the Handlerexceptionresolver interface, the global exception handler needs to implement the interface. To use this own exception handler, we first have to configure the processor in the Springmvc.xml file:

<!--SPRINGMVC provides a simple exception handler--<Bean class=" Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver ">     <!--define the default exception handling page--    < property name="Defaulterrorview" value="/web-inf/jsp/error.jsp" />    <!--Define the name of the variable that the exception handling page uses to get exception information, or it can be undefined, by default named Exception --     < property name="Exceptionattribute" value="Ex"/ >    <!--define exceptions that require special handling, which is important --     < property name="Exceptionmappings">        <props>            <prop key="Ssm.exception.CustomException">/web-inf/jsp/custom_error.jsp</prop>        </props>        <!--can also define additional custom exceptions--    </Property ></Bean>

From the above configuration, the most important thing is to configure special handling exceptions, these exceptions are generally our custom, according to the actual situation from the definition of the exception, and then will jump to different error display page display different error message. A custom exception customexception is used here to illustrate the problem, as defined below:

//Define a simple exception class Public  class customexception extends Exception {    //Exception information     PublicString message; Public customexception(String message) {Super(message); This. message = message; } PublicStringGetMessage() {returnMessage } Public void Setmessage(String message) { This. message = message; }}

The next step is to write a test program, or use an example of a query, as follows:

Then we enter the URL in the foreground to test: http://localhost:8080/SpringMVC_Study/editItems.action?id=11, deliberately passed an ID of 11, my database does not have an ID of 11, So it must not be found, anyway let it can not be found. It then throws out the defined exception and is then captured and executed by the global exception handler configured above, jumps to the page we specify, and then shows that the item does not exist. So this process is very clear.
From the above process, the use of simplemappingexceptionresolver for exception processing, with simple integration, good extensibility (can arbitrarily increase the custom exception and exception display page), the existing code is not invasive, and other advantages, However, the method can only obtain the exception information, if the exception is encountered in the case of the need to obtain data other than the exception is not applicable.

3. Custom Global Exception Handlers

Global exception handler processing ideas:

  1. Parse out exception type
  2. If the exception type is a system-defined exception, remove the exception information directly on the error page to display
  3. Constructs a custom exception type if the exception type is not a system-customized exception (information is "Unknown error")

SPRINGMVC provides a handlerexceptionresolver interface, the custom global exception handler must implement this interface, as follows:

 Public  class customexceptionresolver implements handlerexceptionresolver {    @Override     PublicModelandviewresolveexception(HttpServletRequest request, httpservletresponse response, Object handler, Exception ex)        {Ex.printstacktrace (); Customexception customexception =NULL;//If a system-defined exception is thrown, direct conversion        if(exinstanceofcustomexception) {customexception = (customexception) ex; }Else{//If you throw an exception that is not a system custom, reconstruct an unknown error exception            //Here I also have customexception convenient, in practice should be to define a new exceptionCustomexception =NewCustomexception ("System unknown Error"); }//Return error message to foregroundModelandview Modelandview =NewModelandview (); Modelandview.addobject ("Message", Customexception.getmessage ()); Modelandview.setviewname ("/web-inf/jsp/error.jsp");returnModelandview; }}

The logic in the global exception handler is clear, I'm not going to say more, and then I'm configuring this custom exception handler in Springmvc.xml:

<!-- 自定义的全局异常处理器 只要实现HandlerExceptionResolver接口就是全局异常处理器--><bean class="ssm.exception.CustomExceptionResolver"></bean>

You can then test it again using the test case above. You can see that in a custom exception handler, you can get the object that caused the exception, which is helpful in providing more detailed exception handling information. This custom global exception handler is generally more common.

4. @ExceptionHandler annotations for exception handling

There is a way to use annotations, I probably say the idea, because this method of code intrusion is relatively large, I do not like to use this method.
First write a Basecontroller class and use the @exceptionhandler annotation in the class to declare the method of exception handling, such as:

publicclass BaseController {     @ExceptionHandler      publicexp(HttpServletRequest request, Exception ex) {     //异常处理    //......    }}

All controllers that require exception handling are then inherited by this basecontroller, although it is not necessary to configure anything from execution, but the code is intrusive and the controller that requires exception handling inherits it.
As for the exception handling of SPRINGMVC, let's summarize so much.
  

Related reading: http://blog.csdn.net/column/details/spring-mvc.html
Learning Note Source: Https://github.com/eson15/SpringMVC_Study

-Willing to share and progress together!
--My Blog home: http://blog.csdn.net/eson_15

Unified exception Handling in "Springmvc learning 07" Springmvc

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.