Spring-message converter and spring-Converter

Source: Internet
Author: User

Spring-message converter and spring-Converter

// 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 must implement the AbstractHttpMessageConverter abstract class.

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 acthttpmessageconverter <Phone> {/*** converts the request header data to Phone */@ Override protected Phone readInternal (Class <? Extends Phone> arg0, HttpInputMessage msg) throws IOException, HttpMessageNotReadableException {// The parameter must be submitted using post and InputStream is = msg in the body. 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 conversion Class supported by the current converter */@ Override protected boolean supports (Class <?> Arg0) {if (arg0 = Phone. class) {return true;} return false;}/*** is used to convert the returned object to a string and display it on the webpage */@ Override protected void writeInternal (Phone phone, HttpOutputMessage arg1) throws IOException, HttpMessageNotWritableException {String p = phone. getQno () + "-" + phone. getNumber (); arg1.getBody (). write (p. getBytes ("UTF-8 "));}}

// Configure the bean: Message converter for springmvc. xml. Only the post submission method is blocked by the 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 ht Tp: // 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 Ma/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <! -- Springmvc can only scan the control layer --> <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> <! -- The message converter must use post for submission --> <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: 3:11:27, January 1, July 1, 2017
*/
@ Controller
Public class ReservePageServelt {

 

///**
// * Forward: forward
// * Redirect: Redirection
// * @ 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 ideas,

// The principle is to convert the data in the Request body or request header to the parameters of the action method, and convert the content returned by the method to the response header.
// When the url path is accessed, the @ RequestBody annotation is used. This annotation indicates that this class is to be processed by the message converter. Then, the springmvcxml file reads the message converter and enters the supports method.
// Determine whether the class is supported by the specified converter. If yes, call the readInternal method to cut the class and pass the value to the object. After the processing is completed as an object, it will call writeInternal to convert to the Response Header
@ RequestMapping (value = "/add ")
@ ResponseBody
Public Phone messageConvertor (@ RequestBody Phone, HttpServletResponse response ){
System. out. println (phone. getQno () + phone. getNumber ());
Return phone;

}

}

 

 

Conclusion: The principle of message converter is to convert the data in the Request body to an object and convert the returned content of the method to a response header.

Steps:

When the url path is accessed, the @ RequestBody annotation is used. This annotation indicates that this class is to be processed by the message converter. Then, the message converter is read in the springmvcxml file, and the supports method is entered.
Determines whether the class is supported by the specified converter. If yes, call the readInternal method to cut the class and pass the value to the object.

After the processing is completed as an object, the writeInternal is called to convert it to a response header.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.