A dot eyeball.

The message converter HttpMessageConverter is used to process data in request and Response. Spring built-in the massive HttpMessageConverter for us, for example, MappingJackson2HttpMessageConverter, StringHttpMessageConverter, etc. The following demonstrates a custom HttpMessageConverter and registers this HttpMessageConverter into Spring MVC

Example 2.

1. Customize HttpMessageConverter

package org.light4j.springMvc4.messageconverter; import java.io.IOException; import java.nio.charset.Charset; import org.light4j.springMvc4.domain.DemoObj; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.util.StreamUtils; Public class MyMessageConverter extends AbstractHttpMessageConverter < DemoObj > {/ / (1) public MyMessageConverter () { super(new MediaType("application", "x-longjiazuo",Charset.forName("UTF-8"))); // Override protected DemoObj readInternal(Class<? extends DemoObj> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8")); String[] tempArr = temp.split("-"); return new DemoObj(new Long(tempArr[0]), tempArr[1]); } /** */ @override protected Boolean supports(Class<? > clazz) { return DemoObj.class.isAssignableFrom(clazz); } /** * ⑤ */ @override protected void writeInternal(DemoObj obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { String out = "hello:" + obj.getId() + "-"+ obj.getName(); outputMessage.getBody().write(out.getBytes()); }}Copy the code

Code explanation:

1) inherited AbstractHttpMessageConverter HttpMessageConverter interface to implement custom. ② New application/ X-Longjiazuo for our custom media type. ③ Rewrite the readInternal method to process the requested data. The code says we process the data separated by “-” and turn it into a DemoObj object. HttpMessageConverter only handles DemoObj. ⑤ Rewrite the writeInternal method to handle how to output data to response. In this case, we prefix the original output with “hello:”.

2. The configuration

Add the viewController map to Converter. JSP in the MyMvcConfig method as follows:

registry.addViewController("/converter").setViewName("/converter");Copy the code

The added code looks like this:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/index").setViewName("/index");
    registry.addViewController("/toUpload").setViewName("/upload");
    registry.addViewController("/converter").setViewName("/converter");
}Copy the code

To register HttpMessageConverter in Spring MVC, there are two methods:

1. The configuration in the file MyMvcConfig configureMessageConverters: overloading will overwrite Spring MVC multiple HttpMessageConverter registered by default. 2. Configure extendMessageConverters in the MyMvcConfig file: Add only a custom HttpMessageConverter and do not override the default registered HttpMessageConverter.

So, in this example we override extendMessageConverters to add the following code to the file MyMvcConfig:

@Override public void extendMessageConverters(List<HttpMessageConverter<? >> converters) { converters.add(converter()); } @Bean public MyMessageConverter converter(){ return new MyMessageConverter(); }Copy the code

3. Demonstrate the controller

package org.light4j.springMvc4.web; import org.light4j.springMvc4.domain.DemoObj; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class ConverterController { @RequestMapping(value = "/convert", Produces = {"application/ x-longuo "}) //① public @responseBody DemoObj convert(@requestBody DemoObj DemoObj) { return demoObj; }}Copy the code

Code explanation:

① Specify the returned media type as our custom media type Application/X-Longjiazuo

4. Demo page

New conventer.jsp under SRC /main/ Resources

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>HttpMessageConverter Demo</title> </head> <body> <div id="resp"></div><input type="button" onclick="req();" Value =" request "/> <script SRC ="assets/js/jquery.js" type="text/javascript"></script> <script> function req(){$.ajax({url: "Convert ", data: "1-longjiazuo", //① type:"POST", contentType:"application/x-longjiazuo", //② success: function(data){ $("#resp").html(data); }}); } </script> </body> </html>Copy the code

Code explanation:

① Pay attention to the data format, background processing according to this format, separated by “-“. ② contentType set media type is our custom Application/X-Longjiazuo.

5. Run

accesshttp://localhost/springMvc4.x-httpMessageConverter/converter.As shown below:



Click the Request button and make the following observations.The request type is shown below:



Get our custom data format in the background,As shown below:



The page effect is as follows:

Three. Source code examples:

Github Address: Click to view code cloud address: click to view

exceptional
Welcome to follow the life designer’s wechat public account



longjiazuoA