我的目标是在重定向期间将模型属性从控制器传递到JSP页面,并避免在URL中显示该属性。以下源代码使用Java数据对象验证了来自数据存储区的登录。
控制器:
@Controller public class LoginController { int count; PersistenceManager pm = PMF.get().getPersistenceManager(); //Instance of data class User user; ModelAndView modelAndView=new ModelAndView(); @RequestMapping(value="/Login",method = RequestMethod.POST) public ModelAndView loginValidate(HttpServletRequest req){ //Getting login values String uname=req.getParameter("nameLogin"); String pswd1=req.getParameter("pswdLogin"); count=0; user=new User(); //Generating Query Query q = pm.newQuery(User.class); q.setFilter("userName == userNameParam"); q.declareParameters("String userNameParam"); try{ List<User> results = (List<User>) q.execute(uname); for (User u: results) { String userName=u.getUserName(); if(userName.equals(uname)){ System.out.println(u.getPassword()); if(u.getPassword().equals(pswd1)){ count=count+1; modelAndView.setViewName("redirect:welcome"); modelAndView.addObject("USERNAME",uname); return modelAndView; } //rest of the logic }
JSP:
<h1>Welcome ${USERNAME} </h1>
我当前的URL是/welcome?USERNAME=robin 我的目标是将其显示为/welcome 另外,我的页面应该显示“ Welcome robin”,而仅显示Welcome。
/welcome?USERNAME=robin
/welcome
RedirectAttributes仅适用于RedirectView,请遵循相同的步骤
@RequestMapping(value="/Login",method = RequestMethod.POST) public RedirectView loginValidate(HttpServletRequest req, RedirectAttributes redir){ ... redirectView= new RedirectView("/foo",true); redir.addFlashAttribute("USERNAME",uname); return redirectView; }
这些 flash属性 通过会话传递(并在使用后立即销毁-有关详细信息,请参见Spring参考手册)。这有两个兴趣: