This article is participating in the Java Theme Month – Java Debug Notes EventActive link

preface

Scenario Review: Recently I was debugging an interface with a third party, who kept saying that calling our interface was a repeat submission problem. And this one that we have about repeated submissions is a unified base component; So the underlying component was eliminated in advance; Finally, after investigation, it was found that this component was used to judge whether to submit the second time by obtaining data from the Parameter of the request, but the data in JSON format could not be obtained in this way. However, the interface we provide externally uses JSON format to interact; The JSON format is obtained from the input stream of the request; So the problem found is ultimately a component problem;

validation

  1. Defining interceptors

This interceptor basically gets the data from the request; Here we get data in the stream, and we can also get data in Parameter.

public class TestInterceptor extends HandlerInterceptorAdapter {
    private final Logger logger = LoggerFactory.getLogger(TestInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        BufferedReader reader = request.getReader();
        String line;
        StringBuilder sb = new StringBuilder();
        while((line = reader.readLine()) ! =null) {
            sb.append(line);
        }
        logger.info("Json information: {}", sb.toString());
        return true; }}Copy the code
  1. Register interceptors

Note that there is no option to inherit webMVcConfigurerAdapter because the WebMVcConfigurerAdapter is deprecated; So we use another one

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(newTestInterceptor()); }}Copy the code
  1. Build controller

The @requestBody annotation is used to receive the request data;

@RestController
@RequestMapping("/test")
public class TestController {
    private final Logger logger= LoggerFactory.getLogger(TestController.class);
    @RequestMapping("/one")
    public String get(@RequestBody TestInfoVo testInfoVo){
        logger.info("Controller info: {}",testInfoVo.toString());
        return "SUCCESS"; }}Copy the code

The last

conclusion

  1. The requested data can be easily divided into two categories; One is that the data is in the Parameter of request. One is in the input stream of the request;
  2. The Parameter of the request can be read repeatedly.
  3. The data in the input stream of the request can be read only once. If the data is read repeatedly, additional Settings are required, but the data is not read once.
  4. When using interceptors to process request data, different request data formats should be considered.