重庆找工作哪个网站好,用canvas做网站,seo页面优化技术,宁波江北区建设局网站前些天发现了一个巨牛的人工智能学习网站#xff0c;通俗易懂#xff0c;风趣幽默#xff0c;忍不住分享一下给大家。点击跳转到教程。
ControllerAdvice#xff0c;是spring3.2提供的新注解#xff0c;从名字上可以看出大体意思是控制器增强。让我们先看看ControllerAdv…前些天发现了一个巨牛的人工智能学习网站通俗易懂风趣幽默忍不住分享一下给大家。点击跳转到教程。
ControllerAdvice是spring3.2提供的新注解从名字上可以看出大体意思是控制器增强。让我们先看看ControllerAdvice的实现 Java代码 Target(ElementType.TYPE) Retention(RetentionPolicy.RUNTIME) Documented Component public interface ControllerAdvice { } 没什么特别之处该注解使用Component注解这样的话当我们使用context:component-scan扫描时也能扫描到具体可参考【第十二章】零配置 之 12.3 注解实现Bean定义 ——跟我学spring3。 其javadoc定义是
写道/** * Indicates the annotated class assists a Controller. * * pServes as a specialization of {link Component Component}, allowing for * implementation classes to be autodetected through classpath scanning. * * pIt is typically used to define {link ExceptionHandler ExceptionHandler}, * {link InitBinder InitBinder}, and {link ModelAttribute ModelAttribute} * methods that apply to all {link RequestMapping RequestMapping} methods. * * author Rossen Stoyanchev * since 3.2 */即把ControllerAdvice注解内部使用ExceptionHandler、InitBinder、ModelAttribute注解的方法应用到所有的 RequestMapping注解的方法。非常简单不过只有当使用ExceptionHandler最有用另外两个用处不大。 接下来看段代码 Java代码 ControllerAdvice public class ControllerAdviceTest { ModelAttribute public User newUser() { System.out.println(应用到所有RequestMapping注解方法在其执行之前把返回值放入Model); return new User(); } InitBinder public void initBinder(WebDataBinder binder) { System.out.println(应用到所有RequestMapping注解方法在其执行之前初始化数据绑定器); } ExceptionHandler(UnauthenticatedException.class) // 加上这个注解捕获异常UnauthenticatedException//可以改为其它要捕获的异常类型如 RuntimeException ResponseStatus(HttpStatus.UNAUTHORIZED) public String processUnauthenticatedException(NativeWebRequest request, UnauthenticatedException e) { System.out.println(应用到所有RequestMapping注解的方法在其抛出UnauthenticatedException异常时执行); return viewName; //返回一个逻辑视图名 } } 如果你的spring-mvc配置文件使用如下方式扫描bean Java代码 context:component-scan base-packagecom.sishuok.es use-default-filtersfalse context:include-filter typeannotation expressionorg.springframework.stereotype.Controller/ /context:component-scan 需要把ControllerAdvice包含进来否则不起作用 Java代码 context:component-scan base-packagecom.sishuok.es use-default-filtersfalse context:include-filter typeannotation expressionorg.springframework.stereotype.Controller/ context:include-filter typeannotation expressionorg.springframework.web.bind.annotation.ControllerAdvice/ /context:component-scan 1、ModelAttribute注解的方法作用请参考SpringMVC强大的数据绑定2——第六章 注解式控制器详解——跟着开涛学SpringMVC中的【二、暴露表单引用对象为模型数据】作用是一样的只不过此处是对所有的RequestMapping注解的方法都起作用。当需要设置全局数据时比较有用。
2、InitBinder注解的方法作用请参考SpringMVC数据类型转换——第七章 注解式控制器的数据验证、类型转换及格式化——跟着开涛学SpringMVC同1类似。当需要全局注册时比较有用。
3、ExceptionHandler异常处理器此注解的作用是当出现其定义的异常时进行处理的方法其可以使用springmvc提供的数据绑定比如注入HttpServletRequest等还可以接受一个当前抛出的Throwable对象。可以参考javadoc或snowolf的Spring 注解学习手札八补遗——ExceptionHandler。 该注解非常简单大多数时候其实只ExceptionHandler比较有用其他两个用到的场景非常少这样可以把异常处理器应用到所有控制器而不是Controller注解的单个控制器。