Springmvc Learning (eight) exception handler in--SPRINGMVC

Source: Internet
Author: User

Springmvc exception information is processed by the exception handler during the processing of the request, and the custom exception handler can implement a system exception handling logic.

The idea of abnormal handling

We know that there are two kinds of exceptions in the system: expected exception and run-time exception (RuntimeException), which obtains exception information by catching exception, the latter mainly by standardizing code development, testing by means of reducing the occurrence of run-time exception. The system of DAO, service, controller exception is thrown up through throws exception, and finally by the SPRINGMVC Front 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. Such as:

Understanding the exception handling mechanism in SPRINGMVC, we begin to analyze the exception handling in SPRINGMVC.

Global exception Handler case custom Exception class

In order to distinguish between different exceptions, the exception class is usually customized according to the exception type, where we create a custom system exception, if the Controller, service, DAO throws such exception description is the exception information expected to be handled by the system.
We can write a custom exception class--customerexception.java under the project's Com.itheima.springmvc.exception package, as follows:

 Public classCustomerexceptionextendsException {PrivateString Expmessage;  Publiccustomerexception () {} Publiccustomerexception (String msg) { This. Expmessage =msg; }     PublicString getexpmessage () {returnExpmessage; }     Public voidsetexpmessage (String expmessage) { This. Expmessage =Expmessage; }}
Custom Exception handlers

Global exception handler processing ideas:

    1. Resolves the exception type.
    2. If the exception type is a system-customized exception, the exception information is taken directly and displayed on the error page.
    3. If the exception type is not a system-defined exception, then the wrong stack information should be removed and recorded and displayed on the error page.

SPRINGMVC provides a handlerexceptionresolver interface, the custom global exception handler must implement this interface, So we can write a custom global exception handler under the Com.itheima.springmvc.exception package, as follows:

/*** Global Exception handler *@authorLi Ahi **/ Public classGlobalexceptionresolverImplementsHandlerexceptionresolver {@Override PublicModelandview resolveexception (httpservletrequest request, httpservletresponse response, Object handler, Ex Ception exception) {//Judging the type of anomalyString msg =NULL; if(Exceptioninstanceofcustomerexception) {            //if it is a custom exception, remove the error message from the exceptionCustomerexception Custexp =(customerexception) exception; Msg=Custexp.getexpmessage (); } Else {            //if it is a run-time exception, take the wrong stack informationException.printstacktrace ();//to print stack information to the consoleStringWriter S=NewStringWriter (); PrintWriter PrintWriter=NewPrintWriter (s);            Exception.printstacktrace (PrintWriter); Msg=s.tostring (); }        //Write a log, send a text message, send an email//omit this step here ...//returns a friendly error page and displays an error messageModelandview Modelandview =NewModelandview (); Modelandview.addobject ("MSG", MSG); Modelandview.setviewname ("Error"); returnModelandview; }}

Remember to also provide an error page--error.jsp in the/web-inf/jsp directory, as follows:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><%@ taglib uri=" Http://java.sun.com/jsp/jstl/core "prefix = "C"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >    ${msg}</body> 
Exception Processor Configuration

The logic in the global exception handler is clear, I'll stop talking, and then configure this custom exception handler in the Springmvc.xml file:

class= "Com.itheima.springmvc.exception.GlobalExceptionResolver" ></bean>
Test

The next step is to write the test program, and first transform the Getitemslist method in the Itemcontroller class into:

@RequestMapping ("/itemlist") PublicModelandview getitemslist ()throwsException {//Custom Exception Testing    if(true) {        Throw NewCustomerexception ("This is our custom exception, hahaha ....) "); }    //Check Product ListList<items> itemList =itemservice.getitemlist (); //Pass the query results to the pageModelandview Modelandview =NewModelandview (); Modelandview.addobject ("ItemList", itemList);//The AddObject method is equivalent to putting it on the request domain//Set Logical ViewModelandview.setviewname ("ItemList"); //return Results    returnModelandview;}

Then we enter the URL in the browser to test: Http://localhost:8080/springmvc-web2/item/itemList.action. The Getitemslist method throws a custom exception in any case, then is captured and executed by the global exception handler configured above, and jumps to the page we specify, as follows:

Then the Getitemslist method in the Itemcontroller class is transformed into:

@RequestMapping ("/itemlist") PublicModelandview getitemslist ()throwsException {//tests for run-time exceptions    inti = 1/0; //Check Product ListList<items> itemList =itemservice.getitemlist (); //Pass the query results to the pageModelandview Modelandview =NewModelandview (); Modelandview.addobject ("ItemList", itemList);//The AddObject method is equivalent to putting it on the request domain//Set Logical ViewModelandview.setviewname ("ItemList"); //return Results    returnModelandview;}

Then we enter the URL in the browser to test: Http://localhost:8080/springmvc-web2/item/itemList.action. The Getitemslist method then throws a runtime exception, which is then captured and executed by the global exception handler configured above, and jumps to the page we specify, as follows:

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. As for the exception handling of SPRINGMVC, let's summarize so much.

Springmvc Learning (eight) exception handler in--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.