Spring MVC异常处理 和 重定向传递数据
2024-10-02 18:47:52
1.异常处理介绍
Spring在web项目中,如果在请求处理时出现异常,那输出会是Servlet响应。这时异常需要以某种方式转换为响应。
Spring将异常转换为响应的方式:
a.特定的Spring异常将自动映射为指定的HTTP状态码;
b.异常上添加@ResponseStatus注解,从而将其映射为某一个HTTP状态码;
c.方法上添加@ExceptionHandler注解,使其处理异常。
2.异常处理代码
@RequestMapping("getPathVariable/{id}")
public String getPathVariable(
@PathVariable("id") String id){
if("error".equals(id)){
throw new SpittleException();
}
return "index";
}
package com.taozhiye.controller; import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(
//
value = HttpStatus.NOT_FOUND,
reason = "Spittle not found"
)
public class SpittleException extends RuntimeException { }
正常情况下,当id为error时,会报错,这时是500错误,我们可以通过@ResponseStatus注解,映射到404状态码上,进行简单的异常处理。
第二种方法是报相应的异常,直接跳转到错误页面。
package com.taozhiye.controller; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice
public class AppExcepitonHandler { @ExceptionHandler(Exception.class)
public String deal(){
System.out.println("出现异常");
return "index";
}
}
3.重定向传值
@RequestMapping("getPathVariable/{id}")
public String getPathVariable(
@PathVariable("id") String id,
Model model,
RedirectAttributes model2){
if("error".equals(id)){
throw new SpittleException();
}else if("findAll".equals(id)){
/**
* 重定向传参数:
* 相当于把参数写到session中,
* 如果重定向到controller的时候,用@ModelAttribute接收
* 如果重定向到页面,可以直接接收
*/
model2.addFlashAttribute("flash", "flash");
/**
* 通过url模板进行重定向
*/
return "redirect:/{id}";
}else if("index".equals(id)){
// model.addAttribute("id", id);
/**
* 转发不可以使用模板
*/
// return "/{id}";
model2.addFlashAttribute("flash", "flash");
/**
* 通过url模板进行重定向
*/
return "index";
}else{
return "ajax1";
}
}
@RequestMapping("/findAll")
@ResponseBody
public List<User> findAll(@ModelAttribute("flash") String flash){
System.out.println("flash:"+flash);
return userService.findUserAll();
} @RequestMapping("/index")
@ResponseBody
public List<User> index(Map<String, Object> map,@ModelAttribute("flash")String flash){
System.out.println("flash:"+flash);
return userService.findUserAll();
}
重定向传参数:
相当于把参数写到session中,
如果重定向到controller的时候,用@ModelAttribute接收
如果重定向到页面,可以直接接收
最新文章
- Atitit 游戏的原理与概论attilax总结
- 使用html5 地理位置技术 和 百度地图api查询当前位置
- Git命令行下解决冲突
- how to get soul shields in blade and soul
- java修改图片大小
- 第一章,Linux常用命令
- 【K8s】Kubernetes 最近正在看的资料
- 让MyEclipse2013兼容Retina屏幕
- spring mvc上传图片
- iTween基础之Audio(音量和音调的变化)
- hdu 4691 Front compression (后缀数组)
- .Net Core MVC 过滤器(一)
- 无阻赛的脚本(js脚本延迟方法)
- docker进阶-初探Docker-compose
- [HNOI 2005]狡猾的商人
- nodejs分离html文件里面的js和css
- python 和python-m 的区别
- [zz]LyX 入门教程
- 转---JS 一定要放在 Body 的最底部么?聊聊浏览器的渲染机制
- windows安装python2.7后的注册(registry)问题