一、springmvc相关注解说明:
1、@Controller
负责注册一个bean到spring上下文中
2、@RequestMapping
注解为控制器指定可以处理那些url请求
3、@RequestParam
在处理方法入参处使用,可以把请求参数传递给请求方法
4、@PathVariable
绑定URL占位符到入参
5、@ExceptionHandler
注解到方法上,出现异常时会执行该方法
6、@ContrllerAdvice
是一个controller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有controller发生的异常
二、处理全局异常
@ControllerAdevice
public class testControllerAdevice{
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv=new ModelAndView (“error”);
mv.addObject(“exception”,ex);
System.out.print(“in testControllerAdevice”);
return mv;
}
}
三、异常的处理
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
ModelAndView mv=new ModelAndView (“error”);
mv.addObject(“exception”,ex);
System.out.print(“in testControllerAdevice”);
return mv;
}
四、设置一个自定义拦截器
//创建一个MyInterceptor类,实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest arg0,HttpServletResponse arg1,Object arg2,Exception arg3)throws Exception{
System.out.printIn(“afterCompletion”);
}
@Override
pblic void postHandler(HttpServletRequest arg0,HttpServletResponse arg1,Object arg2, ModelAndView arg3)throws Exception{
System.out.printIn("postHandler");
}
@Override
pblic boolean preHandler(HttpServletRequest arg0,HttpServletResponse arg1,Object arg2)throws Exception{
System.out.printIn("preHandler");
return true;
}
}