Post 方式

1、自動注入

  a. pom.xml ---- 配置Maven,新增必要的jar包

 <!--用於 String-JSONObject 轉換 -->
<dependency>
<groupId>org.json</groupId>
<artifactId>org.json</artifactId>
<version>chargebee-1.0</version>
</dependency> <!--用於 SpringMVC 注入 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.8</version>
<type>jar</type>
<scope>compile</scope>
</dependency>

  b.application-servlet.xml 建立 AnnotationMethodHandlerAdapter

 <!-- 方式1 -->
<mvc:annotation-driven />
<!-- 方式2 -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 兩種方式等價的,mvc:annotation-driven 會自動註冊方式2中的連個bean -->

  c.前端jsp頁面 ---- Jquery的ajax

 <!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
$(function() {
function ajaxtest(){
var seaText = $("#search").attr("value");
var data={};
data.serachdata = seaText;
var url = "${pageContext.request.contextPath}/search1"
$.ajax({
url : url,
type : 'post',
dataType : 'json',
data:JSON.stringify(data),
contentType : "application/json; charset=utf-8",
success:function(result){
console.log(result);
}
}
);
}
$("#search").on("keyup", ajaxtest);
}//end ready
</head>
</script>
<body>
<div>
<input id="search" type="text" name="search">
<input id="btn1"type="submit" value="Search">
</div>
</body>
</html>

  d.Controller 程式碼

  SpringMVC 根據@RequestMapping將前端的ajax請求對映到search 的controller,AnnotationMethodHandlerAdapter會把request中的json物件,採用合適方式自動轉換成Map物件  ★★

 @RequestMapping(value = "search",method = RequestMethod.POST)
@ResponseBody public String search(@RequestBody HashMap<String, String> hasmap)throws Exception{
List<String> resultList = testMapper.searchByKeyWords(hasmap.get("serachdata")+"%");
return new org.json.JSONArray(resultList).toString();
}

2. 通過HttpServletRequest request來接收json

  這種方式是比較常見的這裡,我這給出Controller的程式碼:

 @RequestMapping(value = "search",method = RequestMethod.GET)
@ResponseBody public String search(HttpServletRequest request ,HttpServletResponse response)throws Exception{
org.json.JSONObject jsonob = new JSONObject(request.getParameter("jsonobj"));
List<String> resultList = testMapper.searchByKeyWords("a%");
return new org.json.JSONArray(resultList).toString();
}

Get 方式

  由於get是通過URI傳遞引數的,所以沒有辦法使用自動注入,只能通過request來接收引數,Controller與post方式的類似。

第一篇博文啊!希望大家多多指點....