spring mvc 页面跳转及传值

一、后台接收请求
1.使用HttpServletRequest获取:

@RequestMapping("/login.do")
public String login(HttpServletRequest request){
String name = request.getParameter(“name”)
String pass = request.getParameter(“pass”)
}

2.controller方法的参数值和前台提交的表单的name名称保持一致

@RequestMapping("/login")
public String login(HttpServletRequest request, String name,
@RequestParam(“pass”)String password) { // 表单属性是pass,用变量password接收
syso(name);
syso(password)
}

注:@RequestParam(“pass”)String password:是接收前台表单的pass,重命名为password。

3.后台使用实体类接收
后台实体类:
public class User{
private String name;
private String pass;
}

方法参数可以直接用实体类接收:
@RequestMapping("/login")
public String login(User user)
{
syso(user.getName());
syso(user.getPass());
}

二、后台向页面返回数据或跳转页面
1.ajax请求:

@RequestMapping(value="/getUserTest",method=RequestMethod.POST)
@ResponseBody
public Map getUserTest(UserTest usertestDto){
	Map map = new HashMap();
	UserTest userTestReturn = new UserTest();
	userTestReturn = userTestService.getUserTestByUserName(usertestDto.getUserName());
	map.put("data", userTestReturn);
	return map;
}
*注:想要跳转页面ajax请求的success方法里添加:window.location.href = "/*.jsp"; 并把后台获取到的数据通过参数传过去*

2.form表单请求即跳转页面又携带数据(注:想要用ajax跳转页面就要在ajax请求的success方法里添加:window.location.href = “/*.jsp”;)
2.1使用ModelAndView
@RequestMapping("/login")
public ModelAndView login(String name,String pass){
User user = userService.login(name,pwd);
Map data = new HashMap();
data.put(“user”,user);
return new ModelAndView(“success”,data);
}

2.2使用ModelMap
@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”;
}

2.3使用HttpServletReequest的session
@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 页面跳转及传值)