溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么使用spring的消息轉換器

發布時間:2020-11-25 16:57:54 來源:億速云 閱讀:145 作者:Leah 欄目:編程語言

這篇文章給大家介紹怎么使用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<&#63; 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<&#63;> 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提交方式才會被轉換器攔截

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<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轉換為響應頭

關于怎么使用spring的消息轉換器就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女