客戶端發送的數據:key=value&key1=value1html
響應回來:jsonjava
1 package org.guangsoft.controller; 2
3 import java.util.ArrayList; 4 import java.util.List; 5
6 import org.guangsoft.pojo.User; 7 import org.springframework.stereotype.Controller; 8 import org.springframework.web.bind.annotation.RequestBody; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.ResponseBody; 11
12 @Controller 13 public class UserHandler 14 { 15 //responseBody將返回值轉化爲json格式響應到客戶端 16 //requestBody將請求數據轉化爲json對象
17 @RequestMapping("/checkUsername") 18 public @ResponseBody List<User> CheckUsername(User user) 19 { 20 System.out.println(user.getUsername()); 21 List<User> userList = new ArrayList<User>(); 22 User user0 = new User(); 23 user0.setUsername("java"); 24 User user1 = new User(); 25 user1.setUsername("javase"); 26 User user2 = new User(); 27 user2.setUsername("javaee"); 28 //對象加入集合
29 userList.add(user0); 30 userList.add(user1); 31 userList.add(user2); 32 return userList; 33 } 34
35 @RequestMapping("/checkUsername2") 36 public @ResponseBody List<User> CheckUsername2(@RequestBody User user) 37 { 38 System.out.println(user.getUsername()); 39 List<User> userList = new ArrayList<User>(); 40 User user0 = new User(); 41 user0.setUsername("java"); 42 User user1 = new User(); 43 user1.setUsername("javase"); 44 User user2 = new User(); 45 user2.setUsername("javaee"); 46 //對象加入集合
47 userList.add(user0); 48 userList.add(user1); 49 userList.add(user2); 50 return userList; 51 } 52 }
備註:springmvc ajax,響應json406錯誤,使用json相關jar包2.4以上版本。web
1 function sendAjax() 2 { 3 var username = $("#username").val(); 4 var age = $("#age").val(); 5 var div = $("#showDiv"); 6 $.ajax( 7 { 8 url:"checkUsername.action", 9 data:{"username":username,"age":age}, 10 type:"post", 11 dataType:"json", 12 success:function(data) 13 { 14 var jsons = data; 15 div.html(""); 16 for(var i = 0; i < jsons.length; i++) 17 { 18 div.append("<div>"+jsons[i].username+"</div>"); 19 } 20 } 21 }); 22 }
客戶端發送的數據:{key:value,key1:value1}ajax
響應回來:jsonspring
見上 json
1 function sendAjax2() 2 { 3 var username = $("#username").val(); 4 var age = $("#age").val(); 5 var div = $("#showDiv"); 6 $.ajax( 7 { 8 url:"checkUsername2.action", 9 type:"post", 10 data:'{"username":"username","age":"4"}', 11 contentType:"application/json;charset=utf-8", 12 dataType:"json", 13 success:function(data) 14 { 15 var jsons = data; 16 div.html(""); 17 for(var i = 0; i < jsons.length; i++) 18 { 19 div.append("<div>"+jsons[i].username+"</div>"); 20 } 21 } 22 }); 23 }
Model封裝數據的範圍request範圍,只有請求轉發才能獲取服務器
若是是重定向變爲url傳參。mvc
Return 「forward:url」:請求轉發app
Return 「redirect:url」重定向post