@Controller @RequestMapping("/json") public class jsonController { @ResponseBody @RequestMapping("/user") public User get(){ User u = new User(); u.setId(1); u.setName("jayjay"); u.setBirth(new Date()); return u; } }
十四、异常的处理1.处理局部异常(Controller内)
@ExceptionHandler public ModelAndView exceptionHandler(Exception ex){ ModelAndView mv = new ModelAndView("error"); mv.addObject("exception", ex); System.out.println("in testExceptionHandler"); return mv; } @RequestMapping("/error") public String error(){ int i = 5/0; return "hello"; }
2.处理全局异常(所有Controller)
@ControllerAdvice public class testControllerAdvice { @ExceptionHandler public ModelAndView exceptionHandler(Exception ex){ ModelAndView mv = new ModelAndView("error"); mv.addObject("exception", ex); System.out.println("in testControllerAdvice"); return mv; } }
3.另一种处理全局异常的方法
在SpringMVC配置文件中配置
error
error是出错页面
十五、设置一个自定义拦截器1.创建一个MyInterceptor类,并实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { System.out.println("afterCompletion"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { System.out.println("postHandle"); } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { System.out.println("preHandle"); return true; } }
2.在SpringMVC的配置文件中配置
3.拦截器执行顺序
十六、表单的验证(使用Hibernate-validate)及国际化1.导入Hibernate-validate需要的jar包
(未选中不用导入)2.编写实体类User并加上验证注解
public class User { public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } @Override public String toString() { return "User [id=" + id + ",, birth=" + birth + "]"; } private int id; @NotEmpty private String name; @Past @DateTimeFormat(pattern="yyyy-MM-dd") private Date birth; }
ps:@Past表示时间必须是一个过去值
3.在jsp中使用SpringMVC的form表单
id: name: birth:
ps:path对应name
4.Controller中代码