其他分享
首页 > 其他分享> > SpringMVC_异常处理_@ResponseStatus

SpringMVC_异常处理_@ResponseStatus

作者:互联网

一、异常类 

/**
 * 只有局部全局都不能解决才会使用这个
 */
@ResponseStatus(reason="查询数据失败")//,value = HttpStatus.NOT_ACCEPTABLE
public class BookException extends RuntimeException {

}

二、 Controller

@Controller
public class BookController{
    //不能标注在方法上(正常方法,永远异常)
    //@ResponseStatus(reason="反正我错误了。。。",value= HttpStatus.NOT_EXTENDED)
	@GetMapping("/find")
	public String find(Integer value) throws Exception{
		try {
			int i = 5/value;
			return "success";
		} catch (Exception e) {
			throw new BookException();
		}
	}

    ///**
    // * 告诉SpringMVC这个方法专门处理这个类发生的异常
    // * 1、给方法上随便写一个Exception,用来接受发生的异常
    // * 2、要携带异常信息不能给参数位置写Model;
    // * 3、返回ModelAndView就行了;
    // * 4、如果有多个@ExceptionHandler都能处理这个异常,精确优先
    // * 5、全局异常处理与本类同时存在,本类优先;
    // */
    //@ExceptionHandler(value = { Exception.class })
    //public ModelAndView handleException01(Exception exception) {
    //    System.out.println("本类的:handleException01..." + exception);
    //    //
    //    ModelAndView view = new ModelAndView("myerror");
    //    view.addObject("ex", exception);
    //    // 视图解析器拼串
    //    return view;
    //}
    
}

三、SpringMVC配置文件 

<!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
    如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
<context:component-scan base-package="org.fkit"/>
<!-- 默认配置方案 -->
<mvc:annotation-driven/>
<!-- 静态资源处理 -->
<mvc:default-servlet-handler/>

<!-- 视图解析器  p:prefix属性表示前缀  p:suffix 表示后缀  -->
<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/content/" p:suffix=".jsp"/>

四、发送请求 

<form action="find">
    <input type="text" name="value" value="0">
    <input type="submit">
</form>

五、效果展示

标签:Exception,SpringMVC,value,public,ModelAndView,异常,ResponseStatus,view
来源: https://blog.csdn.net/qq_40794973/article/details/98449081