spring integration之http-rest例子解析(二)

2014-11-24 10:09:05 · 作者: · 浏览: 1
Path Usage
/*


Spring 配置
先看:web-application-config.xml
这个配置里引入了security-config.xml 和 applicationContext-http-int.xml两个配置
并且使用context:component-scan指定自动扫描加载注解的位置。
[html]
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">







我们主要看一下applicationContext-http-int.xml
先配置一个int:annotation,查到其作用是Enables annotation support for Message Endpoints,也就是开启消息端点的注解支持吧。
[html]

inbound gateway's 和 inbound adapter 都需要指定这个,用于其path属性。
[html]

接着指定两个channel通道,一个用于请求一个用于响应。
[html]



下面就是gateway(能翻译为网关么??)了,使用http inbound-gateway来通过http接受信息,关联上之前的两个通道,指定path路径,通过路径解析出参数id.
[html]

supported-methods="GET, POST"
request-channel="employeeSearchRequest"
reply-channel="employeeSearchResponse"
mapped-response-headers="Return-Status, Return-Status-Msg, HTTP_RESPONSE_HEADERS"
view-name="/employee"
path="/services/employee/{id}/search"
reply-timeout="50000">


配置一个ContentNegotiatingViewResolver,其作用主要是使用内容协商来实现多视图,可以参考http://www.cnblogs.com/zhaoyang/archive/2012/01/07/2315428.html这个帖子,详细讲解。大意就是说使用它来支持返回json xml等多种内容形式。

其中用于将对象转为xml的为marshaller,它的contextPath="org.springframework.integration.samples.rest.domain",就是对这个包下的进行转换。
[html]













class="org.springframework.integration.samples.rest.json.view.ExtendedMappingJacksonJsonView" >











用于json的定义一个ExtendedMappingJacksonJsonView
MappingJacksonJsonView输出会返回{model类名:{内容}} 的json格式, 例如期望的返回是 {success:true,message:”return ok”};
但实际返回的却是 {"jsonResult":{"success":true,"msg":"return ok"}}
原因是MappingJacksonJsonView中对返回值的处理未考虑modelMap中只有一个值的情况,直接是按照mapName:{mapResult}的格式来返回数据的。
修改方法如下代码,重载MappingJacksonJsonView类并重写filterModel方法,处理一下map.size为1的情况。
代码如下:
[java]
public class ExtendedMappingJacksonJsonView extends MappingJacksonJsonView {

@SuppressWarnings({"rawtypes" })
@Override
protected Object filterModel(Map model){
Object result = super.filterModel(model);
if (!(result instanceof Map)){
return result;
}

Map map = (Map) result;
if (map.size() == 1){
return map.values().toArray()[0];
}
return map;
}
}


最后定义一个service-activator,关联上两个通道,并关联employeeSearchService的getEmployee方法即可。
[html]
input-