SpingMVC-exception handling

SpingMVC

Exception Handler Annotation

  • test

    • First create a new test method in Spring MVCTest. Java

      @RequestMapping("/testExceptionHandlerExceptionResolver")
      	public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
      		System.out.println("result: " + (10 / i));
      		return "success";
      	}
      
    • Create a new hyperlink in index.jsp

      <a href="testExceptionHandlerExceptionResolver?i=10">Test ExceptionHandlerExceptionResolver</a>

    • Write two methods of exceptions in Spring MVCTest. Java

      	@ExceptionHandler({RuntimeException.class})
      	public ModelAndView handleArithmeticException2(Exception ex){
      	System.out.println("[Abnormal.]: " + ex);
      		ModelAndView mv = new ModelAndView("error");
      		mv.addObject("exception", ex);
      		return mv;
      	}
      	
      	/**
      	 * 1. The parameter of Exception type, which corresponds to the exception object, can be added to the parameter of @ExceptionHandler method.
      	 * 2. @ExceptionHandler Method input cannot be passed into Map. If you want to transmit exception information on the page, you need to use ModelAndView as the return value.
      	 * 3. @ExceptionHandler Exceptions marked by methods have priority issues. The method closest to the exception is found.
      	 * 4. @ControllerAdvice: If the @ExceptionHandler method cannot be found in the current Handler to extract the exception from the current method, 
      	 * The @ExceptionHandler tag will be searched in the @Controller Advice tag class to handle exceptions. 
      	 */
      	@ExceptionHandler({ArithmeticException.class})
      	public ModelAndView handleArithmeticException(Exception ex){
      		System.out.println("Abnormal.: " + ex);
      		ModelAndView mv = new ModelAndView("error");
      		mv.addObject("exception", ex);
      		return mv;
      	}
      
    • When i of the testException Handler Exception Resolver hyperlink is modified to 0, triggering a mathematical exception executes the highest accuracy @Exception Handler ({Arithmetic Exception. class}) exception.

      Page effects

  • @ Controller Advice: If the @ExceptionHandler method cannot be found in the current Handler to extract the exception of the current method,
    The @ExceptionHandler tag will be searched in the @Controller Advice tag class to handle exceptions.

    • The two exception methods of Spring MVCTest. Java should be deleted before testing.

      • Create a new Spring MVCTestExceptionHandler. Java class under the package com.atguigu.springmvc.test

        import org.springframework.web.bind.annotation.ControllerAdvice;
        import org.springframework.web.bind.annotation.ExceptionHandler;
        import org.springframework.web.servlet.ModelAndView;
        
        @ControllerAdvice
        public class SpringMVCTestExceptionHandler {
        
        	@ExceptionHandler({ArithmeticException.class})
        	public ModelAndView handleArithmeticException(Exception ex){
        		System.out.println("----> Abnormal.: " + ex);
        		ModelAndView mv = new ModelAndView("error");
        		mv.addObject("exception", ex);
        		return mv;
        	}
        	
        }
        

Exception Handling _ResponseStatusException Resolver

  • test

    • @ ResponseStatus is added to the class

      • Create a new UserNameNotMatchPasswordException.java class under the com.atguigu.springmvc.test package (customize an exception)

        package com.atguigu.springmvc.test;
        
        import org.springframework.http.HttpStatus;
        import org.springframework.web.bind.annotation.ResponseStatus;
        /*
         * value=HttpStatus.FORBIDDEN This is the status code 403 reason= "User name and password do not match!"
         */
        @ResponseStatus(value=HttpStatus.FORBIDDEN, reason="User name and password do not match!")
        public class UserNameNotMatchPasswordException extends RuntimeException{
        
        	/**
        	 * 
        	 */
        	private static final long serialVersionUID = 1L;
        
        	
        }
        
      • Create a new test method under Spring MVCTest. Java

        @RequestMapping("/testResponseStatusExceptionResolver")
        	public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
        		if(i == 13){
        			throw new UserNameNotMatchPasswordException();
        		}
        		System.out.println("testResponseStatusExceptionResolver...");
        		
        		return "success";
        	}
        
      • Create a corresponding hyperlink in index.jsp

        <a href="testResponseStatusExceptionResolver?i=10">Test ResponseStatusExceptionResolver</a>

        Clicking on the hyperlink and changing i to 13 triggers our custom exception

    • @ ResponseStatues added to methods

      	@ResponseStatus(reason="test",value=HttpStatus.NOT_FOUND)
      	@RequestMapping("/testResponseStatusExceptionResolver")
      	public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
      		if(i == 13){
      			throw new UserNameNotMatchPasswordException();
      		}
      		System.out.println("testResponseStatusExceptionResolver...");
      		
      		return "success";
      	}
      

      At this point, no matter how much i on the hyperlink is changed to, abnormal pages will pop up, but printing is normal.

Exception Handling _DefaultHandler Exception Resolver

  • test

    • Create a new method under Spring MVCTest. Java

      @RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)
      	public String testDefaultHandlerExceptionResolver(){
      		System.out.println("testDefaultHandlerExceptionResolver...");
      		return "success";
      	}
      
    • Add a hyperlink to index.jsp

      <a href="testDefaultHandlerExceptionResolver">Test DefaultHandlerExceptionResolver</a>

    • Clicking on this hyperlink triggers an exception because clicking on the hyperlink is a get request, but the @RequestMapping annotation only allows post requests to access it.

Exception Handling _SimpleMapping Exception Resolver

  • Building a Target Method in Spring MVCTest. Java

    • @RequestMapping("/testSimpleMappingExceptionResolver")
      	public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
      		String [] vals = new String[10];
      		System.out.println(vals[i]);
      		return "success";
      	}
      
  • Which page to turn to when an exception is configured in spring mvc. XML

    • <! -- Configuration uses SimpleMapping Exception Resolver to map exceptions - >
      	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      		<property name="exceptionAttribute" value="ex"></property>
      		<! - ExceptionAttribute is the attribute name value="ex" of an exception, which means that we can change the exceptions we use to ex such as ${requestScope.exception} to ${requestScope. ex} - >.
              <property name="exceptionMappings">
      			<props>
                      <! - Configure pages with abnormal turn-over of arrays - >
      				<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
      			</props>
      		</property>
      	</bean>	
      
  • Add the corresponding hyperlink in index.jsp

    <a href="testSimpleMappingExceptionResolver?i=2">Test SimpleMappingExceptionResolver</a>

    After clicking on the hyperlink, change the i on the hyperlink to 20 (the range of the array in the method is 10), so there is an exception crossing the boundary.

    Because the error page in the xml file is configured with an array crossing abnormal turn, the page turns to the error page.

Keywords: Java Spring JSP xml

Added by timcclayton on Sat, 14 Sep 2019 14:38:58 +0300