在web.xml中添加:
<error-page(其他属性404...省略咯)> <location>/error</location> </error-page>
添加控制器:
@Controller public class ErrorController { @RequestMapping(path = "/error", produces = MediaType.APPLICATION_JSON_VALUE) public ModelAndView handle(HttpServletRequest request) { System.out.println("ERROR"); ModelAndView modelAndView = new ModelAndView("error"); Map<String, Object> map = new HashMap<String, Object>(); map.put("status", request.getAttribute("javax.servlet.error.status_code")); map.put("reason", request.getAttribute("javax.servlet.error.message")); modelAndView.addObject("map", map); return modelAndView; } }
视图:
<html> <head> <title>Title</title> </head> <body> ${map} </body> </html>
这里说一下:
produces = MediaType.APPLICATION_JSON_VALUE
它的作用是指定返回值类型,不但可以设置返回值类型还可以设定返回值的字符编码;
还有一个属性与其对应,就是consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
他们的使用方法如下:
一、produces的例子
produces第一种使用,返回json数据,下边的代码可以省略produces属性,因为我们已经使用了注解@responseBody就是返回值是json数据:
@Controller @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json") @ResponseBody public Pet getPet(@PathVariable String petId, Model model) { // implementation omitted }
produces第二种使用,返回json数据的字符编码为utf-8.:
@Controller @RequestMapping(value = "/pets/{petId}", produces="MediaType.APPLICATION_JSON_VALUE"+";charset=utf-8") @ResponseBody public Pet getPet(@PathVariable String petId, Model model) { // implementation omitted }
二、consumes的例子(方法仅处理request Content-Type为“application/json”类型的请求。)
@Controller @RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json") public void addPet(@RequestBody Pet pet, Model model) { // implementation omitted }