SpringBoot in various configurations WebMvcConfigurationSupport

A, addResourceHandlers static resources

SpringBoot the default / static class path, / resources, / public, / META-INF / resources mapped to the folder / **, you may define a mapping from a path through the addResourceHandlers.

The following Examples more different system environments add different paths, mapped address / imgs / **. Value in the configuration file can also get according to @Value comment.

@Configuration
public class WebMvnConfig extends WebMvcConfigurationSupport {
	@Value("${application.static.res-path}")
	private String resPath;
	
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
        String path = System.getProperty("os.name").equalsIgnoreCase("linux") ? "file:/home/imgs/" : "file:E:/imgs/";
        registry.addResourceHandler("/imgs/**").addResourceLocations(path);
    }
}

This allows access to static resources in the specified path in your browser.
Here Insert Picture Description

Two, addInterceptors interceptor

You can add by addInterceptors interceptor, the interceptor needs to implement HandlerInterceptor interface and processing logic in preHandle returns true not intercept, otherwise interception, interceptor can intercept static resources.

addPathPatterns add a path for blocking, by receiving a variable parameter, excludePathPatterns for excluding paths.

The following code, on / admin / login does not intercept the addition, the rest are intercepted. In addition 2.jpg, the rest are interception and interception / imgs / down.
In preHandle simple request to determine whether the user is a parameter passed away the night listening to the wind and pass as abc123, otherwise interception, this time should jump to another interface.

@Configuration
public class WebMvnConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("preHandle------------->"+request.getRequestURL());
                /**
                 * 逻辑处理
                 */
                /**
                 * 返回true则不拦截,false则拦截
                 */
               boolean result = request.getParameter("user")
                       .equals("听风逝夜") && request.getParameter("pass").equals("abc123");
               if (!result){
                   response.sendRedirect("/admin/login");
               }
                return result;
            }
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                //在Controller处理完之后回调,preHandle返回false则不走这里
                System.out.println("postHandle------------>");
            }
            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                //整个请求处理完毕回调方法,preHandle返回false则不走这里
                System.out.println("afterCompletion-------------->");
            }
        }).addPathPatterns("/admin/**","/imgs/**").excludePathPatterns("/imgs/2.jpg","/admin/login");
    }
}

Three, addCorsMappings add cross-domain configuration

However, this method has the feeling and @CrossOrigin pit, or filter to solve cross-domain issues now.

   @Override
   protected void addCorsMappings(CorsRegistry registry) {
       super.addCorsMappings(registry);
       registry.addMapping("/**")
               .allowedOrigins("*")
               .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
               .allowCredentials(true)
               .allowedHeaders("*")
               .maxAge(3600);
   }

Four, addViewControllers add view controller

When accessing a page might have done that in the Controller

  @GetMapping("/")
  public String index(){
      return "index";
  }

But there is no logic, not each write it, so can be used to solve addViewControllers

 @Override
 protected void addViewControllers(ViewControllerRegistry registry) {
     super.addViewControllers(registry);
     registry.addViewController("/").setViewName("/index");
 }

It is equal to the above two methods.

Five, resolveArgument parameter parser

If you want to implement custom analytical parameters, such as the date in the following format resolve to LocalDateTime, you can add a HandlerMethodArgumentResolver resolved resolveArgument in.
Here Insert Picture Description
First define a comment.

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Date {
    String value();
    boolean required() default true;
}

Second, add a HandlerMethodArgumentResolver implementation class, in supportsParameter determine whether the need to convert, that is, to see if there are comments on our custom parameters. If it returns true, the method proceeds resolveArgument, conversion, the return value is set to the original SpringBoot parameter. If the return is inconsistent on the type and the original parameters, an error.

The following example determines whether Date annotation to customize the parameters, then it continues resolveArgument method is first acquired value the value of the annotation, and then obtain the corresponding value in the url by NativeWebRequest, if the null or split size is not 5, the process returns null, otherwise converted into LocalDateTime type and return.

@Configuration
public class WebMvnConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(new HandlerMethodArgumentResolver() {
            @Override
            public boolean supportsParameter(MethodParameter methodParameter) {
                return methodParameter.hasParameterAnnotation(Date.class);
            }
            @Override
            public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                          NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
                Date date =methodParameter.getParameterAnnotation(Date.class);
                String parameter = nativeWebRequest.getParameter(date.value());
                if (parameter!=null){
                    String[] split = parameter.split(",");
                    if (split.length==5){
                        return LocalDateTime.of(converInteger(split[0]),converInteger(split[1]),converInteger(split[2]),converInteger(split[3]),converInteger(split[4]));
                    }
                }
                return null;
            }
        });
    }
    private Integer converInteger(String param){
        return Integer.valueOf(param);
    }
}

Then it can be used in the method, together with comments on @Date parameters, date = 2020,2,18,8,8 can receive date data format

@GetMapping("/")
public String index(@Date("date") LocalDateTime date){
    System.out.println("index"+date);
    return "index";
}

Six, addReturnValueHandlers return value processing

Can be converted into json returned by @ResponseBody objects, so you want to do this, there is an annotation, mark on the Controller method will return the object of xml format data. Implementation can add a HandlerMethodReturnValueHandler in addReturnValueHandlers in.

First, write a note, indicating the return value is xml type.

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ResponseXmlBody {
}

Next, the method supportsReturnType HandlerMethodReturnValueHandler whether there is a determination method ResponseXmlBody annotations on, the process proceeds to true handleReturnValue.

o handleReturnValue the return value of the parameter is the Controller method after reflection by a series of operations, spliced ​​into an xml format data, and using the acquired nativeWebRequest output stream, provided Content-Type is text / plain; charset = utf-8 but here we must set modelAndViewContainer.setRequestHandled (true) ;.

@Configuration
public class WebMvnConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
        super.addReturnValueHandlers(returnValueHandlers);
        returnValueHandlers.add(new HandlerMethodReturnValueHandler() {
            @Override
            public boolean supportsReturnType(MethodParameter methodParameter) {
                return methodParameter.hasMethodAnnotation(ResponseXmlBody.class);
            }
            @Override
            public void handleReturnValue(Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
                modelAndViewContainer.setRequestHandled(true);
                HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
                response.addHeader("Content-Type", "text/plain;charset=utf-8");
                Class<?> aClass = o.getClass();
                StringBuffer value =new StringBuffer();
                Field[] declaredFields = aClass.getDeclaredFields();
                for (int i = 0; i < declaredFields.length; i++) {
                    declaredFields[i].setAccessible(true);
                    addNode(value,declaredFields[i].getName(),declaredFields[i].get(o));
                }
                StringBuffer rootStringBuffer =new StringBuffer();
                addNode(rootStringBuffer,aClass.getSimpleName(),value);
                response.getWriter().append(rootStringBuffer);
            }
        });
    }
    private void addNode(StringBuffer stringBuffer,String name,Object value){
        stringBuffer.append("<");
        stringBuffer.append(name);
        stringBuffer.append(">");
        stringBuffer.append(value);
        stringBuffer.append("<");
        stringBuffer.append(name);
        stringBuffer.append(">");
        stringBuffer.append("\n");
    }
 }

The final output is as follows. The above code can not be rehabilitated level target analysis, if you want to complete their own or use the framework oh.
Here Insert Picture Description

Seven, addFormatters format

Such as the use @RequestParam reception Book object, url format is:? Book = title, such a price, @ RequestParam not translate directly, you can customize the format be solved by addFormatters.

String s parse method is the parameter corresponding to the url.

@Configuration
public class WebMvnConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        super.addFormatters(registry);
        registry.addFormatter(new Formatter<Book>() {
            @Override
            public Book parse(String s, Locale locale) throws ParseException {
                String[] split = s.split(",");
                if (split.length==2){
                    return  new Book(split[0],Float.valueOf(split[1]));
                }
                return null;
            }
            @Override
            public String print(Book book, Locale locale) {
    
                return null;
            }
        });
    }
 }
 public class Book {
    public Book() {
    }

    public Book(String bookName, Float price) {
        this.bookName = bookName;
        this.price = price;
    }

    private String bookName;
    private Float price;

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
}

  @GetMapping("addBook")
  @ResponseBody
  public Object date(@RequestParam("book")Book book){
      System.out.println(book);
      return book;
  }

Output follows
Here Insert Picture Description

Published 42 original articles · won praise 7 · views 7739

Guess you like

Origin blog.csdn.net/HouXinLin_CSDN/article/details/104370727