zoukankan      html  css  js  c++  java
  • 详解Springboot中自定义SpringMVC配置

    详解Springboot中自定义SpringMVC配置

    WebMvcConfigurer接口

    ​ 这个接口可以自定义拦截器,例如跨域设置、类型转化器等等。可以说此接口为开发者提前想到了很多拦截层面的需求,方便开发者自由选择使用。由于Spring5.0废弃了WebMvcConfigurerAdapter,所以WebMvcConfigurer继承了WebMvcConfigurerAdapter大部分内容。

    WebMvcConfigurer接口中的方法

    file

    举例1:configurePathMatch配置请求后缀是否包含.*来映射请求

    @Configuration
    public class WebMVCConfiguration implements WebMvcConfigurer {
    
        /**
         * 是否包含.*来映射请求
         * 假设RequestMapping注解中指定的路径是/test
         * 如果设置成True,那么对于/test.do,/test.a等任何包含.的请求都会映射到/test上去;
         * 如果设置成False,那么对于这种请求不会进行映射。
         *
         */
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            configurer.setUseSuffixPatternMatch(true);
        }
    
    
    }
    

    结果:

    file

    举例2:configureHandlerExceptionResolvers配置全局异常处理器

        @Override
        public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
                resolvers.add(new HandlerExceptionResolver() {
                    @Override
                    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
                        BaseResult baseResult = new BaseResult();
                        if(e instanceof MissingServletRequestParameterException) {
                            baseResult.setCode(-1);
                            baseResult.setMessage("系统参数异常,请联系管理员");
                        }
    
                        httpServletResponse.setCharacterEncoding("UTF-8");
                        httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
                        try {
                            httpServletResponse.getWriter().write(JSON.toJSONString(baseResult));
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                        return new ModelAndView();
                    }
                });
        }
    

    结果:

    file

  • 相关阅读:
    UITableView全面解析
    UITableView传值(自己使用)(属性,代理传值)
    页面之间传值(单例传值)(自己使用)
    带导航栏的最简单多视图
    UIscrollView和UIPageControl的循环滚动
    UIPickerView简单应用
    自定义进度条(菜鸟版)
    UISegmentedControl(人物简介)
    UI控件闪灯
    关于NSCELL
  • 原文地址:https://www.cnblogs.com/undefined22/p/12657852.html
Copyright © 2011-2022 走看看