spring-訊息轉換器,spring-轉換器

來源:互聯網
上載者:User

spring-訊息轉換器,spring-轉換器

//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;    }    }

//訊息轉換器  要實現一個抽象類別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> {    /**     * 將要求標頭資料轉換成Phone     */        @Override    protected Phone readInternal(Class<? extends Phone> arg0,            HttpInputMessage msg) throws IOException,            HttpMessageNotReadableException {        //參數必須使用post提交必須在body中        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;    }    /**     * 當前的轉換器支援轉換的類     */    @Override    protected boolean supports(Class<?> arg0) {        if(arg0==Phone.class){            return true;        }        return false;    }    /**     * 用於將返回的對象轉換成字串顯示在網頁     */    @Override    protected void writeInternal(Phone phone, HttpOutputMessage arg1)            throws IOException, HttpMessageNotWritableException {        String p=phone.getQno()+"-"+phone.getNumber();        arg1.getBody().write(p.getBytes("UTF-8"));    }}

//springmvc.xml 要配置bean:訊息轉換器,只有post提交方式才會被轉換器攔截

<?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只能掃描控制層  -->    <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>        <!--訊息轉換器 必須使用post提交   -->    <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測試


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
* 建立時間:2017年7月1日下午3:11:27
*/
@Controller
public class ReservePageServelt {


// /**
// * forward:轉寄
// * 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);
//}


//訊息轉換器思路,

//原理就是將請求體或者要求標頭的資料轉換為action方法的參數,同時將方法的傳回值的內容轉換為回應標頭
//當url路徑訪問過來時,看到使用了@RequestBody註解,這個註解標識這個類要被訊息轉換器處理,就會springmvcxml檔案中讀到訊息轉換器,然後進入supports方法
//判斷這個類是否被指定的轉換器支援,如果支援,就調用readInternal方法,進行切割,然後將值傳遞到對象中,處理完成為對象之後,就會調用writeInternal轉換為回應標頭
@RequestMapping(value="/add")
@ResponseBody
public Phone messageConvertor( @RequestBody Phone phone,HttpServletResponse response) {
System.out.println(phone.getQno()+phone.getNumber());
return phone;

}

}

 

 

總結:訊息轉換器的原理就是,自訂將請求體的資料轉換為形參(對象),然後將方法的傳回值內容轉換為回應標頭

步驟:

當url路徑訪問過來時,看到使用了@RequestBody註解,這個註解標識這個類要被訊息轉換器處理,就會springmvcxml檔案中讀到訊息轉換器,然後進入supports方法
判斷這個類是否被指定的轉換器支援,如果支援,就調用readInternal方法,進行切割,然後將值傳遞到對象中.

處理完成為對象之後,就會調用writeInternal轉換為回應標頭

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.