The spring message converter USES detail

  • 2020-08-22 22:05:31
  • OfStack

This article shares the specific code of spring message converter for your reference, the specific content is as follows

//domain


package com.crazy.goods.tools;
/**
 * 0755-351512
 * @author Administrator
 *
 */
public class Phone {
  private String qno;
  private String number;
  public String getQno() {
    return qno;
  }
  public void setQno(String qno) {
    this.qno = qno;
  }
  public String getNumber() {
    return number;
  }
  public void setNumber(String number) {
    this.number = number;
  }
  
}

// The message converter implements an abstract class AbstractHttpMessageConverter


package com.crazy.goods.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

public class MyMessageConvertor extends AbstractHttpMessageConverter<Phone> {

  /**
   *  Converts the request header data to Phone
   */
  
  @Override
  protected Phone readInternal(Class<? extends Phone> arg0,
      HttpInputMessage msg) throws IOException,
      HttpMessageNotReadableException {
    // Parameters must be used post Submission must be made in body In the 
    InputStream is=msg.getBody();
    BufferedReader br=new BufferedReader(new InputStreamReader(is));
    String param=br.readLine();
    String phone=param.split("=")[1];
    Phone phoneObj=new Phone();
    phoneObj.setQno(phone.split("-")[0]);
    phoneObj.setNumber(phone.split("-")[1]);
    return phoneObj;
  }
  /**
   *  The current converter supports transformed classes 
   */
  @Override
  protected boolean supports(Class<?> arg0) {
    if(arg0==Phone.class){
      return true;
    }
    return false;
  }
  /**
   *  Used to convert the returned object into a string to display on a web page 
   */
  @Override
  protected void writeInternal(Phone phone, HttpOutputMessage arg1)
      throws IOException, HttpMessageNotWritableException {
    String p=phone.getQno()+"-"+phone.getNumber();
    arg1.getBody().write(p.getBytes("UTF-8"));
  }

}

// ES14en. xml to configure bean: Message converter, only post submission will be intercepted by converter


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    ">
  <!--springmvc Only the control layer can be scanned  -->
  <context:component-scan base-package="com.crazy.goods">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
  </context:component-scan>
  
  <!-- Message converter   You must use the post submit   -->
  <mvc:annotation-driven>
    <mvc:message-converters>
      <bean class="com.crazy.goods.tools.MyMessageConvertor">
        <property name="supportedMediaTypes">
          <list>
            <value>text/html;charset=UTF-8</value>
             <value>application/x-www-form-urlencoded</value>
          </list>
        </property>
      </bean>
    </mvc:message-converters>
  </mvc:annotation-driven>
</beans>

servlet test


package com.crazy.goods.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.crazy.goods.tools.Phone;

/**
* @author Administrator
*  Creation time: 2017 years 7 month 1 On the afternoon 3:11:27
*/
@Controller
public class ReservePageServelt {

// /**
// * forward: forwarding 
// * redirect: redirect 
// * @param req
// * @param resp
// * @return
// * @throws ServletException
// * @throws IOException
// */
// @RequestMapping(value="/add",method={RequestMethod.GET})
// public String doGet(HttpServletRequest req, HttpServletResponse resp/*,@PathVariable("testid") String testid*/) throws ServletException, IOException {
// req.getRequestDispatcher("/reversegood.jsp").forward(req, resp);
// return "/reversegood.jsp";
// resp.getWriter().print(testid);
// }


// Message converter thinking, 

// The principle is to convert the data in the request body or request header to action Method, and converts the contents of the method's return value to the response header 
// when url When path access comes over, see used @RequestBody Annotation that identifies the class to be processed by the message converter springmvcxml Read the message converter in the file, then enter supports methods 
// Determines whether the class is supported by the specified converter and, if so, calls readInternal Method, and then passes the value to the object , After processing is done as an object, it is called writeInternal Convert to response headers 
@RequestMapping(value="/add")
@ResponseBody
public Phone messageConvertor( @RequestBody Phone phone,HttpServletResponse response) {
System.out.println(phone.getQno()+phone.getNumber());
return phone;

}

}

Summary: The message converter works by customizing the data in the request body into formal parameters (objects), and then converting the return value content of the method into the response header

Steps:

When the url path is accessed and you see the @ES31en annotation used, which identifies the class to be processed by the message converter, you read the message converter in the springmvcxml file and enter the supports method
Determines whether the class is supported by the specified converter, and if so, calls the readInternal method, cuts, and passes the value into the object.

Once the processing is complete as an object, writeInternal is called to convert to the response header


Related articles: