目标:基于SpringMVC+Json+Ajax,实现RESTFul (新一代架构风格,简洁是其sell point,方便get / post 数据在浏览器与服务器间的流转)
大体例子:
annomvc-servlet.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd ">
...
<!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
<context:component-scan base-package="com.testproj.base.web.controller" />
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
TopicTagServiceController.java (位于web.controller目录下)
@Controller
@RequestMapping("/topic")
public class TopicTagServiceController {
...
@RequestMapping(value = "/topicTag/group/add", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> insertOrUpdateTopicTagGroup(@RequestBody Map<String, Object> paramMap) {
Map<String, Object> map = new HashMap<String, Object>();
String groupName = (String) paramMap.get("groupName");
...
map.put("message", topicTagGroup.getTopicTagGroupId());
return map;
}
Corresponding JS
tryPost('/topic/topicTag/group/add', {name:$('#groupName').val().trim(), description:$('#groupDesc').val()}, function(data){
...
function tryPost(url, params, successCallBack, failCallBack , withoutGroupId,noShowAlert) {
url = pretreatmentUrl(url , withoutGroupId);
$.ajax({
url : url,
type : "post",
dataType : "json",
contentType : "application/json",
data : params,//必要时可以加上转换函数 json2string()
success : function(data, textStatus) {
...
});
}
function pretreatmentUrl(url,withoutGroupId) {
url = server_url + url; // server_url is the project's basePath
return url;
}
the final URL - e.g. /test_proj/base/topic/topicTag/group/add
Reference: http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/, http://blog.csdn.net/greensurfer/article/details/19296247, http://www.blogjava.net/soken/articles/371548.html