1静态资源映射:
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //addResourceLocations指的是文件放置的目录,addResourceHandler指的是对外暴露的访问路径 registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/"); }2拦截器配置:
定义拦截器:
public class DemoInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { long startTime=System.currentTimeMillis(); request.setAttribute("startTime",startTime); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { long startTime=(Long) request.getAttribute("startTime"); request.removeAttribute("startTime"); long endTime=System.currentTimeMillis(); System.out.println("本次请求处理时间为:"+new Long(endTime-startTime)+"ms"); request.setAttribute("handlingTime",endTime-startTime); } }
//匹配某些路径 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(demoInterceptor()).addPathPatterns("/**") .excludePathPatterns( "/anno/*"); }3@ControllerAdvice的使用(具体用法看注解):
/**组合了Component注解 * 将对控制器的全局配置放置在同一个位置 * 注解了该注解的类可以使用@ExceptionHandler,@InitBinder,@ModelAttribute注解到方法上 * 着对所有注解了@RequestMapping的控制器内的方法有效 */ @ControllerAdvice public class ExceptionHandlerAdvice { /** * 该注解用于全局处理控制器里的异常 * @param exception * @param request * @return */ @ExceptionHandler(value = Exception.class) public ModelAndView exception(Exception exception, WebRequest request){ ModelAndView modelAndView=new ModelAndView("error"); modelAndView.addObject("errorMessage",exception.getMessage()); return modelAndView; } //可以让全局的@RequestMapping都能获取到此处设置的键值对 @ModelAttribute public void addAttributes(Model model){ model.addAttribute("msg","额外信息"); } /** * 该注解用来设置WebDataBinder,WebDataBinder用来自动绑定前台请求参数到Model中,该方法会忽略request参数的id * @param webDataBinder */ @InitBinder public void initBinder(WebDataBinder webDataBinder){ webDataBinder.setDisallowedFields("id"); } }测试例子:
@Controller public class AdviceController { @RequestMapping("/advice") public String getSomething(@ModelAttribute("msg") String msg,DemoObj obj){ throw new IllegalArgumentException("非常抱歉,参数有误/"+"来自@ModelAttribute:"+msg); } }4快捷的ViewController:
如果页面跳转无业务逻辑,只是简单的页面转向,可以通过重写addViewControllers来简化配置
@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index").setViewName("index"); }