当前位置: 移动技术网 > IT编程>开发语言>Java > spring消息转换器使用详解

spring消息转换器使用详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了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转换为响应头

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网