1. Automatic model binding
1.1 先建立Model object, ex: UserProfile
1.2 Form的欄位名稱要跟Model欄位名稱相同.
ex: <form method="POST"><input name="userName" type="text" /></form>
1.3 Controller的寫法如下:
@RequestMapping(method=RequestMethod.POST) public ModelAndView processSubmit(UserProfile user ) { System.out.println(user.getUserName()) ;
//以下程式供回傳用 ModelAndView mav = new ModelAndView("successView") ; mav.addObject("user", user) ; return mav ; }
//以下程式供回傳用 ModelAndView mav = new ModelAndView("successView") ; mav.addObject("user", user) ; return mav ; }
1.4 View中呈現Controller回傳值的方式為:<c:out value="${user.userName}">或直接寫${user.userName}寫也可以.
2. Request Parameter
2.1 Controller的寫法如下:(Form為<form method="POST"><input name="userName" type="text" /></form>)
@RequestMapping(method=RequestMethod.POST)
public ModelAndView processSubmit(@RequestParam(value="userName")String userName) {
System.out.println(userName) ;
//以下程式供回傳用
ModelAndView mav = new ModelAndView("successView") ;
mav.addObject("userName", userName) ;
return mav ;
}
public ModelAndView processSubmit(@RequestParam(value="userName")String userName) {
System.out.println(userName) ;
//以下程式供回傳用
ModelAndView mav = new ModelAndView("successView") ;
mav.addObject("userName", userName) ;
return mav ;
}
2.2 View中呈現Controller回傳值的方式為:<c:out value="${userName}">或直接寫${userName}也可以
3. HttpServletRequest
3.1 Controller的寫法如下:(Form為<form method="POST"><input name="userName" type="text" /></form>)
@RequestMapping(method=RequestMethod.POST)
public ModelAndView processSubmit(HttpServletRequest req) {
System.out.println(req.getParameter("userName")) ;
...
}
public ModelAndView processSubmit(HttpServletRequest req) {
System.out.println(req.getParameter("userName")) ;
...
}
沒有留言:
張貼留言