1.1 请求字符串响应json
客户端发送的数据:key=value&key1=value1
响应回来:json
1.1.1json的支持jar包
1.1.2建立Handler处理器
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 }
1.1.3完成ajax发送请求
备注:springmvc ajax,响应json406错误,使用json相关jar包2.4以上版本。
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 }
1.2请求json响应json
客户端发送的数据:{key:value,key1:value1}
1.2请求json响应json
客户端发送的数据:{key:value,key1:value1}
响应回来:json
1.2.1 建立服务器端Handler
见上
1.2.2客户端发生ajax请求
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 }
2url跳转
Model封装数据的范围request范围,只有请求转发才能获取
如果是重定向变为url传参。
Return “forward:url”:请求转发
Return “redirect:url”重定向