接收參數的方式:
1.HttpServletRequest方式接收
1
2
3
4
5
6
7
|
public ModelAndView test1(HttpServletRequest req){ String userName = req.getParameter( "userName" ); String password = req.getParameter( "password" ); System.out.println(userName); System.out.println(password); return new ModelAndView( "jsp/hello" ); } |
2.@RequestParam方式
1
2
3
4
5
|
public ModelAndView test2(String userName, @RequestParam ( "password" ) String pwd){ System.out.println(userName+ "," +pwd); return new ModelAndView( "jsp/hello" ); } |
3.對象的方式接收
1
2
3
4
|
public ModelAndView test3(User user){ System.out.println(user); return new ModelAndView( "jsp/hello" ); } |
4.
1
2
3
4
5
6
7
8
9
10
|
/** * 使用ModelAndView傳出參數 內部 HttpServletRequest的Attribute傳遞 到jsp頁面 * ModelAndView(String viewName,Map data)data是處理結果 */ @RequestMapping ( "action" ) public ModelAndView test4(User user){ Map<String, Object> data = new HashMap<String, Object>(); data.put( "user" , user); return new ModelAndView( "jsp/hello" ,data); } |
5. Session的方式
1
2
3
4
5
6
7
8
9
|
/** * session存儲 可以使用HttpServletRequest的getSession方法訪問 */ @RequestMapping ( "action" ) public ModelAndView test7(HttpServletRequest req){ HttpSession session = req.getSession(); session.setAttribute( "salary" , 6000.0 ); return new ModelAndView( "jsp/hello" ); } |
6.重定向:
1
2
3
4
5
6
7
8
9
|
@RequestMapping ( "/updateitem" ) //spirngMvc可以直接接收pojo類型:要求頁面上input框的name屬性名稱必須等于pojo的屬性名稱 public ModelAndView updateitem(Items items){ itemsService.updateitems(items); //不可以加斜杠 解析不了 itemList.action return new ModelAndView( new RedirectView( "itemList.action" )); } |
7.重定向
1
2
3
4
5
6
7
8
|
@RequestMapping ( "/updateitem" ) //spirngMvc可以直接接收pojo類型:要求頁面上input框的name屬性名稱必須等于pojo的屬性名稱 public String updateitem(Items items){ itemsService.updateitems(items); //重定向到action 可以加斜杠 redirect:/itemList.action 解析的了 return "redirect:itemList.action" ; } |
使用Model和ModelMap的效果一樣,如果直接使用Model,springmvc會實例化ModelMap。
如果使用Model則可以不使用ModelAndView對象,Model對象可以向頁面傳遞數據,View對象則可以使用String返回值替代。不管是Model還是ModelAndView,其本質都是使用Request對象向jsp傳遞數據。
以上這篇SpringMvc接收參數方法總結(必看篇)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。