SpringMVC异常处理-实例展示1(局部异常处理)




项目结构

pom.xml


    4.0.0
    com.mvc
    spring-mvc-exception-handler
    0.0.1-SNAPSHOT
    war
    
        
            org.springframework
            spring-webmvc
            4.3.9.RELEASE
        
        
            javax.servlet
            servlet-api
            2.5
            provided
        
    

web.xml



    spring-mvc-exception-handler
    
        DispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
        
            contextConfigLocation
            classpath:spring-*.xml
        
        1
    
    
    
        DispatcherServlet
        *.do
    

spring-mvc.xml



    
    
    
    
        
        
        
    

UserController.java

package com.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user/")
public class UserController {
    @RequestMapping("update")
    @ResponseBody
    public String update(Integer id){
        System.out.println("update user");
        if(id==null)
            throw new RuntimeException("id can not be null");
        return "update ok!";
        
    }
    /**
     * 定义Controller中的异常处理方法
     * 借助ExceptionHandler注解进行描述
     * 注解中的内容表示这个方法能够处理的异常类型(包括这个异常的子类类型)
     * @param e
     * @return
     */
    @ExceptionHandler(value=Exception.class)
    @ResponseBody
    public String handleException(Exception e){
        return e.getMessage();
    }
}

http://localhost/spring-mvc-exception-handler/user/update.do


控制台

update user

http://localhost/spring-mvc-exception-handler/user/update.do?id=1


控制台

update user

你可能感兴趣的:(SpringMVC异常处理-实例展示1(局部异常处理))