使用POJO作為參數(shù)
springmvc會自動把參數(shù)注入到POJO對象的屬性中,且包括級聯(lián)注入
<body>
<form action="springmvc/testPojo" method="post"><!-- 提交路徑不要以/開關(guān) -->
用戶名:<input type="text" name="name"><br>
密碼:<input type="password" name="password"><br>
年齡:<input type="text" name="age"><br>
省份:<input type="text" name="address.province"><br>
城市:<input type="text" name="address.city"><br>
<button type="submit">登錄</button>
</form>
</body>
@RequestMapping("/testPojo")
public String testPojo(User user){
System.out.println(user);
return SUCCESS;
}
@Data
@AllArgsConstructor
public class User {
private String name;
private String password;
private int age;
private Address address;
}
使用原生servlet作為參數(shù)
支持的其他類型有
HttpServletRequest
HttpServletResponse
HttpSession
java.security.Principal
Locale
InputStream
OutputStream
Reader
Writer
<a href="springmvc/testServletApi?username='George'">testServletApi</a>
@RequestMapping("/testServletApi")
public void testServletApi(
HttpServletRequest request
,HttpServletResponse response) throws IOException{
String name = request.getParameter("username");
response.getOutputStream().write(name.getBytes());
}
傳參 @ModelAttribute修改數(shù)據(jù)
<form action="springmvc/modifyEmp" method="post">
編號:<input type="text" name="id" value="1"><br>
姓名:<input type="text" name="name" value="Bruce"><br>
<!-- 性別:<input type="text" name="sex" ><br>
注意:該性別組件不能寫,因為我們不希望修改Emp的性別屬性
-->
<button type="submit">修改</button>
</form>
@ModelAttribute
public void getEmp(
@RequestParam(value="id",required=false) Integer id
,Map<String,Object>map){
//0.先從表單提交的數(shù)據(jù)中取出id,存在則繼續(xù)
if (id!=null){
//1.模擬到數(shù)據(jù)庫中查詢是否具有該id的Emp
//2.假設(shè)已經(jīng)查到了,emp是從數(shù)據(jù)庫中取回來的數(shù)據(jù)
Emp emp = new Emp(2,"Smith","man");//數(shù)據(jù)庫中的原始數(shù)據(jù)
map.put("emp", emp);
}
}
@RequestMapping("/modifyEmp")
public String testModelAttribute(Emp emp){
System.out.println("修改后:"+emp);
return SUCCESS;
}
修改的后的數(shù)據(jù):${requestScope.emp}
//修改的后的數(shù)據(jù):Emp(id=1, name=Bruce, sex=man)
SpringMVC 確定目標(biāo)方法 POJO 類型入?yún)⒌倪^程
1. 確定一個 key:
* 目標(biāo)方法的 POJO 類型的參數(shù)有沒有使用 @ModelAttribute 作為修飾, 有則 key 為 POJO 類名首字母小寫的字符串
* 若@ModelAttribute設(shè)置了value值, 則 key 為 @ModelAttribute 注解的 value 屬性值.
2. 在 implicitModel(@ModelAttribute修飾方法的model對象) 中查找 key 對應(yīng)的對象, 若存在, 則作為入?yún)魅?/em>
* 若在 @ModelAttribute 標(biāo)記的方法中用 Map或Model 保存過與1中key同名的對象,那么將會獲取到該對象并傳入
3. 若 implicitModel 中不存在 key 對應(yīng)的對象, 則檢查當(dāng)前的Controller是否使用 @SessionAttributes 注解修飾
* 若使用了該注解, 且 @SessionAttributes 注解的 value 屬性值中包含了該key, 則會從 HttpSession 中來獲取 key 所對應(yīng)的數(shù)據(jù)。若包含了該key但沒有對應(yīng)的數(shù)據(jù)則將拋出異常.
4. 若 Controller 沒有@SessionAttributes 注解或 @SessionAttributes 注解的 value 值中不包含該key
* 會通過反射來創(chuàng)建 POJO 類型的參數(shù), 傳入為目標(biāo)方法的參數(shù)
*5. SpringMVC 會把 key 和 POJO 類型的對象保存到 implicitModel 中, 進(jìn)而會保存到 request 中. *