相關鏈接
HttpServlet 對象,主要包括HttpServletRequest 、HttpServletResponse 和HttpSession 對象
@RequestMapping("requestWried") public void requestWried(HttpServletResponse response, HttpServletRequest request, HttpSession session){ System.out.println(response); System.out.println(request); System.out.println(session); }
前提:
1.傳入的參數類型要匹配
2.參數的名稱,必須要與方法的參數列表的名稱保持一致
@RequestMapping("simpleDataBindOne") public ModelAndView simpleDataBindOne(Integer id, String isAdmin, String type, ModelAndView modelAndView) {...}
前端
<a href="${pageContext.request.contextPath}/requestParam/simpleDataBindOne.action?id=1&isAdmin=1&type=admin">
參數綁定注解
主要是給參數名不同的參數進行相應綁定
@RequestMapping("simpleDataBindTwo") public ModelAndView simpleDataBindTwo(@RequestParam("ids") Integer id, ModelAndView modelAndView) {...}
<a href="${pageContext.request.contextPath}/requestParam/simpleDataBindTwo.action?ids=123">
public class User { private Integer id; private String username; private String sex; private Date birthday; //toString\getter\setter }
請求參數綁定,將請求參數綁定到對象中
要求: 請求參數名稱在User對象中存在,則SpringMVC會自動將參數設置給對象,並且請求參數名和實體名相同即可
@RequestMapping("dataBindPojo") public ModelAndView dataBindPojo(User user, ModelAndView modelAndView) {...}
<a href="${pageContext.request.contextPath}/requestParam/dataBindPojo.action?id=3&username=波波&sex=女">
public class UserVo { private User user; private List<User> userList; private Map<String,User> userMap; // toString,getter,setter }
分別對實體中的User對象,List集合,Map集合賦值
@RequestMapping("dataBindPojoVoList") public ModelAndView dataBindPojoVoList(UserVo userVo, ModelAndView modelAndView) {...}
封裝到User對象中
<a href="${pageContext.request.contextPath}/requestParam/dataBindPojoVo.action?user.id=1&user.username=柳岩&user.sex=女">測試</a>
封裝到List對象中
<form action="${pageContext.request.contextPath}/requestParam/dataBindPojoVoList.action" method="post"> 用戶【1】: 用戶id : <input type="text" name="userList[0].id"/><br> 用戶名稱 : <input type="text" name="userList[0].username"/><br> 用戶性別 : <input type="text" name="userList[0].sex"/><br> 用戶【2】: 用戶id : <input type="text" name="userList[1].id"/><br> 用戶名稱 : <input type="text" name="userList[1].username"/><br> 用戶性別 : <input type="text" name="userList[1].sex"/><br> <input type="submit" value="提交"> </form>
封裝到Map對象中
<form action="${pageContext.request.contextPath}/requestParam/dataBindPojoVoMap.action" method="post"> 用戶【1】: 用戶id : <input type="text" name="userMap['k1'].id"/><br> 用戶名稱 : <input type="text" name="userMap['k1'].username"/><br> 用戶性別 : <input type="text" name="userMap['k1'].sex"/><br> 用戶【2】: 用戶id : <input type="text" name="userMap['k2'].id"/><br> 用戶名稱 : <input type="text" name="userMap['k2'].username"/><br> 用戶性別 : <input type="text" name="userMap['k2'].sex"/><br> <input type="submit" value="提交"> </form>
當使用@RequestMapping URI template 樣式映射時, 即 someUrl/{paramId}, 這時的paramId可通過 @Pathvariable注解綁定它傳過來的值到方法的參數上。
示例代碼:
@Controller @RequestMapping("/owners/{ownerId}") public class RelativePathUriTemplateController { @RequestMapping("/pets/{petId}") public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { // implementation omitted } }
上面代碼把URI template 中變量 ownerId的值和petId的值,綁定到方法的參數上。若方法參數名稱和需要綁定的uri template中變量名稱不一致,需要在@PathVariable("name")指定uri template中的名稱。
@Controller @RequestMapping ( "/test/{variable1}" ) public class MyController { @RequestMapping ( "/showView/{variable2}" ) public ModelAndView showView( @PathVariable String variable1, @PathVariable ( "variable2" ) int variable2) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName( "viewName" ); modelAndView.addObject( " 需要放到 model 中的屬性名稱 " , " 對應的屬性值,它是一個對象 " ); return modelAndView; } }
URI 模板就是在URI 中給定一個變量,然后在映射的時候動態的給該變量賦值。如URI 模板http://localhost/app/{variable1}/index.html ,這個模板里面包含一個變量variable1 ,那么當我們請求http://localhost/app/hello/index.html 的時候,該URL 就跟模板相匹配,只是把模板中的variable1 用hello 來取代。這個變量在SpringMVC 中是使用@PathVariable 來標記的。在SpringMVC 中,我們可以使用@PathVariable 來標記一個Controller 的處理方法參數,表示該參數的值將使用URI 模板中對應的變量的值來賦值。
代碼中我們定義了兩個URI 變量,一個是控制器類上的variable1 ,一個是showView 方法上的variable2 ,然后在showView 方法的參數里面使用@PathVariable 標記使用了這兩個變量。所以當我們使用/test/hello/showView/2.do 來請求的時候就可以訪問到MyController 的showView 方法,這個時候variable1 就被賦予值hello ,variable2 就被賦予值2 ,然后我們在showView 方法參數里面標注了參數variable1 和variable2 是來自訪問路徑的path 變量,這樣方法參數variable1 和variable2 就被分別賦予hello 和2 。方法參數variable1 是定義為String 類型,variable2 是定義為int 類型,像這種簡單類型在進行賦值的時候Spring 是會幫我們自動轉換的。
使用ajax發送請求
<a href="javascript:void(0)" id="id2">ajaxName</a>
$("#id2").click(function () { //JavaScript的對象 let user = {name: "迪麗熱巴", age: "女", birthday: "2001-01-09"}; //變為json的字符串, let userStr = JSON.stringify(user); //contentType //類型:String 默認值: "application/x-www-form-urlencoded"。發送信息至服務器時內容編碼類型。 //dataType 設置接收參數類型 console.log(userStr) $.ajax({ url: "${pageContext.request.contextPath}/ajaxName", type: "post", data: userStr, dataType: "json", contentType: "application/json;charset=UTF-8", success: function (response) { // alert(response); console.log(response); }, error: function (error) { // alert(error); } }); });
這里有兩個步驟需要注意,第一個就是將js的json對象轉成了json數組,第二個就是添加了 contentType: "application/json;charset=UTF-8",這兩個是使用@RequestBody的必須設置。
只有application/json; 和 application/xml; 才是請求體中的數據。
java代碼
@RequestMapping(value = "ajaxReqTest", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST) @ResponseBody public User ajaxReq(@RequestBody User user) { System.out.println(user); return user; }
@ResponseBody 是控制返回的,如果導入了jackson包那么可以根據返回類型進行映射,如返回對象或集合那么就映射為json。
補充一點,如果導入了jackson包,那么@RequestBody 在映射參數時也會自動適配,比如 前端傳一個String 的日期 “2019-01-01”,后端的對象中是一個Date類型,那么可以自動轉換。
下面展示 @ResponseBody 注解除了映射對象之外的其他情況
7.1 直接接受字符串
$.ajax({ ... data: "迪麗熱巴", contentType: "application/json;charset=UTF-8", ... });
@RequestMapping("oneString") @ResponseBody public String oneString(@RequestBody String name){ System.out.println(name); return name; }
7.2 接收字符串數組 映射到數組或List
$.ajax({
... data: JSON.stringify(["q", "w", "e"]), contentType: "application/json;charset=UTF-8",
...
});
//接受數組或list @RequestMapping("toArrString") @ResponseBody public List<String> toArrString(@RequestBody List<String> str) { System.out.println(str); return str; }
@RequestMapping("toArrString") @ResponseBody public String[] toArrString(@RequestBody String[] str) { System.out.println(str); return str; }
7.3 對象數組
$.ajax({ ... data: JSON.stringify([{name: "111", age: "111", birthday: "2019-01-01"},{name: "222", age: "222", birthday: "2019-01-01"}]), contentType: "application/json;charset=UTF-8",
...
});
//接收User數組 @RequestMapping("toArrPojo") @ResponseBody public List<User> toArrPojo(@RequestBody List<User> users){ users.forEach(System.out::println); return users; }
@RequestMapping("toArrPojo") @ResponseBody public List<Map<String,String>> toArrPojo(@RequestBody List<Map<String,String>> users){ users.forEach(System.out::println); return users; }
7.4 復雜情況 嵌套 json嵌套對象和數組
@Data @AllArgsConstructor @NoArgsConstructor public class Complex { private String name; private User user; private List<User> arrStr; private Map<String, Integer> mapStr; }
$.ajax({
...
data: JSON.stringify({
name: "111",
user: {name: "222", age: "222", birthday: "2019-01-01"},
arrStr: [
{name: "333", age: "333", birthday: "2019-01-01"},
{name: "444", age: "444", birthday: "2019-01-01"}
],
mapStr: {num1: 1, num2: 2}
}),
contentType: "application/json;charset=UTF-8",
....
});
@RequestMapping("toComplex") @ResponseBody public Complex toComplex(@RequestBody Complex complex) { System.out.println(complex); return complex; }