springmvc之HttpMessageConvter<T>

1, using HttpMessageConvter <T> may be bound to the request information and converts into a coherent processing method or the type of response to the result converted into the corresponding response information. spring offers two ways:

  • @RequestBody and @ResponseBody method to mark
  • HttpEntity <T> and ResponseEntity <T> into a processing method parameter return value

2, when the controller and the method used to @RequestBody @ResponseBody or HttpEntity <T> and ResponseEntity <T> time, spring HttpMessageConverter according to the first matching attributes Accept request header or response header, in accordance with further parameters of the filter type or generic type get matching HttpMessageConverter, if no available HttpMessageConverter an error.

3, @ RequestBody and @ResponseBody do not need to appear in pairs.

First, you can use the @RequestBody and @ResponseBody to turn into a form of type String, note that this is not for file upload.

    @ResponseBody
    @RequestMapping("/testHttpMessageConverter")
    public String testHttpMessageConverter(@RequestBody String body) {
        System.out.println(body);
        return "hello world"+new Date();
    }

front end:

    <form action="testHttpMessageConverter" method="POST" enctype="multipart/form-data">
        File:<input type="file" name="file"><br>
        Desc:<input type="text" name="desc"><br>
        <input type="submit" value="submit">
    </form>

Second, the use HttpEntity <T> and ResponseEntity <T> Simulation

    @RequestMapping("/testResponseEntity")
    public ResponseEntity<byte []> testResponseEntity(HttpSession session) throws IOException{
        byte [] body = null;
        ServletContext servletContext = session.getServletContext();
        InputStream in = servletContext.getResourceAsStream("/file/tmp.txt");
        body = new byte[in.available()];
        in.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=tmp.txt");
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body,headers,statusCode);
        return response;
    }

Front page:

<a href="testResponseEntity">testResponseEntity</a>

Tmp.txt will download the file in WebContent / file folder After clicking

Guess you like

Origin www.cnblogs.com/xiximayou/p/12188025.html