赞
踩
HttpMessageConveter 是用来处理request 和response 里的数据的。Spring 为我们内置了大量的HttpMessageConverter,例如, MappingJackson2HttpMessageConverter 、StringHttpMessageConverter 等。我们实现一个自定义的HttpMessageConverter,他将接收以“-”号连接的数据,将数据转换成自定义的对象。
package com.example.spring.framework.converter.domain;
/**
* Author: 王俊超
* Date: 2017-07-11 22:07
* All Rights Reserved !!!
*/
public class DemoObj {
private Long id;
private String name;
public DemoObj() {
super();
}
public DemoObj(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.example.spring.framework.converter.controller;
import com.example.spring.framework.converter.domain.DemoObj;
import org.springframework.stereotype.Controller;
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;
/**
* Author: 王俊超
* Date: 2017-07-13 07:56
* All Rights Reserved !!!
*/
@Controller
public class ConverterController {
/**
* 指定返回的媒体类型为我们自定义的媒体类型application/x惆wisely
*/
@RequestMapping(method = RequestMethod.POST, value = "/convert",
produces = "application/x-wisely")
public @ResponseBody
DemoObj converter(@RequestBody DemoObj obj) {
return obj;
}
}
package com.example.spring.framework.converter.config;
import com.example.spring.framework.converter.MyMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import java.util.List;
/**
* Author: 王俊超
* Date: 2017-07-12 07:22
* All Rights Reserved !!!
*/
@Configuration
@EnableWebMvc
@ComponentScan("com.example.spring.framework.converter")
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
super.addResourceHandlers(registry);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/converter").setViewName("/converter");
}
/**
* 配置自定义的HttpMessageConverter 的Bean ,在Spring MVC 里注册HttpMessageConverter有两个方法:
* 1、configureMessageConverters :重载会覆盖掉Spring MVC 默认注册的多个HttpMessageConverter
* 2、extendMessageConverters :仅添加一个自定义的HttpMessageConverter ,不覆盖默认注册的HttpMessageConverter
* 在这里重写extendMessageConverters
*/
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(converter());
}
@Bean
public MyMessageConverter converter() {
return new MyMessageConverter();
}
}
package com.example.spring.framework.converter;
import com.example.spring.framework.converter.domain.DemoObj;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* 继承AbstractHttpMessageConverter 接口来实现自定义的HttpMessageConverter
* Author: 王俊超
* Date: 2017-07-13 07:44
* All Rights Reserved !!!
*/
public class MyMessageConverter extends AbstractHttpMessageConverter<DemoObj> {
public MyMessageConverter() {
// 新建一个我们自定义的媒体类型application/x-wisely
super(new MediaType("application", "x-wisely", Charset.forName("UTF-8")));
}
@Override
protected boolean supports(Class<?> clazz) {
// 表明本HttpMessageConverter 只处理DemoObj 这个类。
return DemoObj.class.isAssignableFrom(clazz);
}
/**
* 重写readlntenal 方法,处理请求的数据。代码表明我们处理由“四”隔开的数据,并转成 DemoObj 的对象。
*/
@Override
protected DemoObj readInternal(Class<? extends DemoObj> clazz,
HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException {
String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
String[] tempArr = temp.split("-");
return new DemoObj(new Long(tempArr[0]), tempArr[1]);
}
/**
* 重写writeInternal ,处理如何输出数据到response。此例中,我们在原样输出前面加上"hello :"。
*/
@Override
protected void writeInternal(DemoObj demoObj,
HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
String out = "hello: " + demoObj.getId() + "-" + demoObj.getName();
outputMessage.getBody().write(out.getBytes());
}
}
package com.example.spring.framework.converter;
import com.example.spring.framework.converter.config.MyMvcConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
/**
* Author: 王俊超
* Date: 2017-07-11 21:51
* All Rights Reserved !!!
*/
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MyMvcConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",
new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HttpMessageConverter Demo</title>
</head>
<body>
<div id="resp"></div>
<input type="button" onclick="req();" value="请求"/>
<script src="assets/assets.js/jquery.assets.js" type="text/javascript"></script>
<script>
function req() {
$.ajax({
url: "convert",
data: "1-wangjunchao", // 注意这里的数据格式,后台处理按此格式处理,用“-”隔开。
type: "POST",
contentType: "application/x-wisely", // contentType 设置的媒体类型是我们自定义的application/x-wisely
success: function (data) {
$("#resp").html(data);
}
});
}
</script>
</body>
</html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。