美文网首页
Spring-MVC

Spring-MVC

作者: 充满智慧的白痴 | 来源:发表于2019-12-30 10:29 被阅读0次

    监听器初始化ioc

    // spring-web.jar包,用于初始化ioc容器
    // 类路径
    // CLASS_PATH 环境变量就是jdk自带的jar包所在的路径比如String
    // 提供初始化容器的配置文件所在的位置默认值applicationContext.xml
    // tomcat全局的配置参数
    <context-param>
         <context-name>contextConfigLocation</context-name>
          // classpath:指向src类路径,就是我们源码的位置
         <context-value>classpath:applicationContext.xml</context-value>
    </context-param>
    <listener>
      // tomcat启动时,自动可以初始化ioc容器
      <listener-class>org.springframework.web.context.ContextLoaderListener.class</listener-class>
    </listener>
    

    配置文件拆分

    <context-param>
         <context-name>contextConfigLocation</context-name>
          // 引入多个配置文件合并
         <context-value>
            classpath:applicationContext.xml,
            classpath:applicationContext2.xml,
            classpath:applicationContext3.xml,
            classpath:applicationContext*.xml
        </context-value>
    </context-param>
    // 获取在配置文件中使用import标签,但不推荐
    

    @ControllerAdvice全局异常拦截

    @RestController
    @ControllerAdvice
    public class GlobalExceptionHandler {
        @ResponseBody
        @ExceptionHandler(TdopRunTimeException.class)
        public Result<?> handleTdopRuntimeException(HttpServletRequest req, TdopRunTimeException e) {
            return Result.fail(e.getCode(), e.getMessage());
        }
    //被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 被 @RequestMapping 注解的方法上。
    

    @RestControllerAdvice返回结果集修改

    public class GlobalResultAdvice implements ResponseBodyAdvice<Object> {
        @Override
        public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
            // 如果该请求接口的类上或者方法上有ResponseBody的注解,就拦截
            return (              
    AnnotatedElementUtils.hasAnnotation(methodParameter.getContainingClass(), ResponseBody.class)
    ||methodParameter.hasMethodAnnotation(ResponseBody.class));
        }
        @Override
        public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType medisaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
            // 统一处理结果集
            if (!(body instanceof com.tdop.common.Result)){
                body = Result.success(body);
            }
            return body;
        }
    }
    ps:需要注意,此处的异常在异常拦截之前,且需要注意类型转换器message-converters的转换顺序,不然会报类型转换错误
    

    相关文章

      网友评论

          本文标题:Spring-MVC

          本文链接:https://www.haomeiwen.com/subject/rriepctx.html