常用的註解學習
參數綁定(簡單類型、pojo、集合類型)
自定義參數綁定(掌握)
Spring參數綁定過程
從客戶端請求key/value數據,經過參數綁定,將key/value數據綁定到controller方法的形參上。
springmvc中,接收頁面提交的數據是通過方法形參來接收。而不是在controller類定義成員變量接收!!!!
默認支持的類型
直接在controller方法形參上定義下邊類型的對象,就可以使用這些對象。在參數綁定過程中,如果遇到下邊類型直接進行綁定。
HttpServletRequest
通過request對象獲取請求信息
HttpServletResponse
通過response處理響應信息
HttpSession
通過session對象得到session中存放的對象
Model/ModelMap
model是一個接口,modelMap是一個接口實現 。
作用:將model數據填充到request域。
簡單類型
通過@RequestParam對簡單類型的參數進行綁定。
(1)要求請求中傳入key/value類型的參數的參數名稱和controller方法的形參名稱一致,方可綁定成功;
(2)如果不想要鍵值對的key和contruller方法形參名一致,可以使用註解 @RequestParam,通過required屬性指定參數是否必傳;如果傳入參數爲空,則取默認值defaultValue的值填充。
@RequestMapping(value = "/editItems", method = { RequestMethod.POST,RequestMethod.GET })
public String editItems(Model model,@RequestParam(value = "id", required = true, defaultValue="1") Integer items_id ) throws Exception {}
pojo綁定
頁面表單中各種文本框的name值和對應pojo類的屬性名要一致,只需在controller的方法中形參定義爲pojo類的類型即可綁定對應參數到該pojo的屬性中;
不管表單是get、post提交方式,還是超鏈接,默認都是 key/value 的形式提交的,contentType="application/x-www-form-urlencoded"
注意:形參中既有簡單類型又有pojo類型,沒關係,參數綁定互不影響。
-------------------------------------------------------------------------------------------------------------------------------------------------------
亂碼問題
GET請求亂碼解決方法有兩個:
(1)修改tomcat配置文件添加編碼與工程編碼一致,如下:(但不推薦)
<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
(2)另外一種方法對參數進行重新編碼:
ISO8859-1是tomcat默認編碼,需要將tomcat編碼後的內容按utf-8編碼
String userName new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8");
POST亂碼解決:
在web.xml添加post亂碼filter
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
以上可以解決post請求亂碼問題。