springmvc @SessionAttributes @ModelAttribute 取session值问题

springmvc @SessionAttributes  @ModelAttribute 取session值问题


public class User implements Serializable{
private String id;


@Controller
@SessionAttributes(Constants.USER_INFO_SESSION)
public class LoginControll {
@RequestMapping(value = "login.html", method = RequestMethod.POST)
	public String login(
			@RequestParam(value = "username", required = false) String username,
			@RequestParam(value = "password", required = false) String password,
			@ModelAttribute(Constants.USER_INFO_SESSION)SysUser user,
			HttpSession session
			Model model) {
		
			SysUser user = userService.validateLogin(username, password);
			System.out.println(user.getId());
			model.addAttribute(Constants.USER_INFO_SESSION);
			return Constants.RESULT_SUCCESS;
      
     }
}

输出: 11000

@Controller
@RequestMapping("/User")
@SessionAttributes(Constants.USER_INFO_SESSION)
public class UserControll {

public @ResponseBody List<?> list(
     @RequestParam(value = "node", required = false)String node,
	 @ModelAttribute(Constants.USER_INFO_SESSION)SysUser user,
	 HttpSession session
      ) {
	System.out.println("user.getId():"+user.getId());
	User u = (User)session.getAttribute(Constants.USER_INFO_SESSION);
	System.out.println("u.getId():"+u.getId());

输出:
user.getId():00
u.getId():00

session去USER对象id值变成了'00'

发现请求参数中有同名id,值是'00'
@Controller
@RequestMapping("/User")
@SessionAttributes(Constants.USER_INFO_SESSION)
public class UserControll {

public @ResponseBody List<?> list(
     @RequestParam(value = "node", required = false)String node,
	 @RequestParam(value = "id", required = false)String id,
	 @ModelAttribute(Constants.USER_INFO_SESSION)SysUser user,
	 HttpSession session
      ) {
        System.out.println("id:" + id);
	System.out.println("user.getId():"+user.getId());
	User u = (User)session.getAttribute(Constants.USER_INFO_SESSION);
	System.out.println("u.getId():"+u.getId());

输出:
id:00
user.getId():00
u.getId():00

请求中参数有同名id,会覆盖session中所有对象同名属性值

改成如下
@Controller
@RequestMapping("/User")
public class UserControll {

public @ResponseBody List<?> list(
     @RequestParam(value = "node", required = false)String node,
	 @RequestParam(value = "id", required = false)String id,
	 HttpSession session
      ) {
        System.out.println("id:" + id);
	User u = (User)session.getAttribute(Constants.USER_INFO_SESSION);
	System.out.println("u.getId():"+u.getId());

输出:
id:00
u.getId():11000

你可能感兴趣的:(java,springMVC)