Spring接收請求參數(shù):
1,使用HttpServletRequest獲取
Java代碼
-
@RequestMapping("/login.do")
-
public String login(HttpServletRequest request){
-
String name = request.getParameter("name")
-
String pass = request.getParameter("pass")
-
}
2,Spring會自動將表單參數(shù)注入到方法參數(shù),,和表單的name屬性保持一致。和Struts2一樣
Java代碼
-
@RequestMapping("/login.do")
-
public String login(HttpServletRequest request,
-
String name,
-
@RequestParam("pass")String password) // 表單屬性是pass,用變量password接收
-
{
-
syso(name);
-
syso(password)
-
}
3,自動注入Bean屬性
Java代碼
-
<form action="login.do">
-
用戶名:<input name="name"/>
-
密碼:<input name="pass"/>
-
<input type="submit" value="登陸">
-
</form>
-
-
//封裝的User類
-
public class User{
-
private String name;
-
private String pass;
-
}
Java代碼
-
@RequestMapping("/login.do")
-
public String login(User user)
-
{
-
syso(user.getName());
-
syso(user.getPass());
-
}
向頁面?zhèn)髦担?/strong>
當Controller組件處理后,,向jsp頁面?zhèn)髦担?/strong>
1,,使用HttpServletRequest 和 Session 然后setAttribute(),就和Servlet中一樣
2,,使用ModelAndView對象
3,,使用ModelMap對象
4,使用@ModelAttribute注解
Model數(shù)據(jù)會利用HttpServletRequest的Attribute傳值到success.jsp中
Java代碼
-
@RequestMapping("/login.do")
-
public ModelAndView login(String name,String pass){
-
User user = userService.login(name,pwd);
-
Map<String,Object> data = new HashMap<String,Object>();
-
data.put("user",user);
-
return new ModelAndView("success",data);
-
}
使用ModelMap參數(shù)對象示例:
ModelMap數(shù)據(jù)會利用HttpServletRequest的Attribute傳值到success.jsp中
Java代碼
-
@RequestMapping("/login.do")
-
public String login(String name,String pass ,ModelMap model){
-
User user = userService.login(name,pwd);
-
model.addAttribute("user",user);
-
model.put("name",name);
-
return "success";
-
}
使用@ModelAttribute示例
在Controller方法的參數(shù)部分或Bean屬性方法上使用
@ModelAttribute數(shù)據(jù)會利用HttpServletRequest的Attribute傳值到success.jsp中
Java代碼
-
@RequestMapping("/login.do")
-
public String login(@ModelAttribute("user") User user){
-
//TODO
-
return "success";
-
}
-
-
@ModelAttribute("name")
-
public String getName(){
-
return name;
-
}
Session存儲:
可以利用HttpServletReequest的getSession()方法
Java代碼
-
@RequestMapping("/login.do")
-
public String login(String name,String pwd
-
ModelMap model,HttpServletRequest request){
-
User user = serService.login(name,pwd);
-
HttpSession session = request.getSession();
-
session.setAttribute("user",user);
-
model.addAttribute("user",user);
-
return "success";
-
}
Spring MVC 默認采用的是轉(zhuǎn)發(fā)來定位視圖,,如果要使用重定向,,可以如下操作
1,使用RedirectView
2,,使用redirect:前綴
Java代碼
-
public ModelAndView login(){
-
RedirectView view = new RedirectView("regirst.do");
-
return new ModelAndView(view);
-
}
或者用如下方法,,工作中常用的方法:
Java代碼
-
public String login(){
-
//TODO
-
return "redirect:regirst.do";
-
}
|