HttpServletRequestWrapper,HandlerMethodArgumentResolver,ResponseBodyAdvice,WebMvcConfigurerAdapter

HttpServletRequestWrapper    

package com.example.springboot.core;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Map;


@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
    private String body;
    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
       // body=getBodyStr(request);
    }

    public String getBodyStr(){
        return  body;
    }
//方法1
//  private String getBodyStr(HttpServletRequest request) throws IOException {
//
//      BufferedReader reader=request.getReader();
//      String line=null;
//      StringBuilder stringBuilder=new StringBuilder();
//       while ((line=reader.readLine())!=null){
//
//           stringBuilder.append(line);
//       }
//       return stringBuilder.toString();
//
//  }
  //方法2
    private String getBodyStr(HttpServletRequest request) throws IOException {

        InputStreamReader reader=new InputStreamReader(request.getInputStream());
        int line=0;
        StringBuilder stringBuilder=new StringBuilder();
        while ((line=reader.read())!=-1){
            stringBuilder.append((char) line);
           log.info("par="+(char)line);
        }
        return stringBuilder.toString();

    }

    /*重写getParameterValues方法
     * 通过循环取出每一个请求结果
     * 再对请求结果进行过滤*/
    @Override
    public Map<String,String[]> getParameterMap() {
        log.info("getParameterValues.123");
        Map<String,String[]> map=super.getRequest().getParameterMap();
        log.info("map={}", JSON.toJSONString(map));
       return map;
    }

    @Override
   public Object getAttribute(String var1){
        log.info("getAttribute.123={}",var1);
        return  var1;
    }

}
View Code
package com.example.springboot.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


@Slf4j
//@Component
@WebFilter
@Order(1)
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

         HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
         RequestWrapper requestWrapper=new RequestWrapper(httpServletRequest);
          // log.info("aaa={}",requestWrapper.getBodyStr());
           //servletResponse.getOutputStream().write("abc001".getBytes(StandardCharsets.UTF_8));
       // httpServletRequest.getParameterMap();
        filterChain.doFilter(servletRequest ,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
View Code
HandlerMethodArgumentResolver
package com.example.springboot.core;

import com.example.springboot.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Date;

@Service
@Slf4j
public class UserArgumetResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
       Boolean result=methodParameter.getParameterType()== User.class;
 log.info("supportsParameter.reuslt={}",result);
        return result;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
         User user=new User();
         user.setUserId(1);
         user.setLastIp("127.0.0.1");
         user.setLastVisit(new Date());
         user.setUserName("abc");
         user.setCredits(100);
         user.setPassword("***");
        return user;
    }
}
ResponseBodyAdvice
package com.example.springboot.common;

import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class CommonResultAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Result<Object> result=new Result<>();
        result.setCode(200);
        result.setMsg("ok");
        result.setData(body);
        if (body instanceof  String){
            return JSON.toJSONString(result);
        }
        return result;
    }
}
View Code
WebMvcConfigurerAdapter
package com.example.springboot.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;


@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    UserArgumetResolver userArgumentResolver;
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(userArgumentResolver);
    }

}
View Code

 

posted @ 2023-03-10 13:43  甜菜波波  阅读(22)  评论(0编辑  收藏  举报