在Spring MVC中重定向期间传递模型属性,并在URL中避免相同

我是spring的新手
我也在stackoverflow中搜索过web和相关post。 我找不到我真正需要的那个。
我的目标是在重定向期间将模型属性从控制器传递到jsp页面,并避免在URL中显示属性。
以下是使用jdovalidation从数据存储区登录。

我的控制器:

@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 results = (List) 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:

  

Welcome ${USERNAME}

我的url是/ welcome?USERNAME = robin
我的目标是将其表示为/ welcome
此外,我的页面应显示“欢迎知识”,而它只显示欢迎。 请让我知道如何解决它。
提前致谢!

您应该使用Spring MVC的flash属性工具。 如果希望在重定向后可以访问数据,则不要将其添加到模型( ModelModelMapModelAndView )中,而是添加到您在控制器方法中作为参数获取的RedirectAttributes

 @RequestMapping(value="/Login",method = RequestMethod.POST) public ModelAndView loginValidate(HttpServletRequest req, RedirectAttributes redir){ ... modelAndView.setViewName("redirect:welcome"); redir.addFlashAttribute("USERNAME",uname); return modelAndView; } 

这些flash属性通过会话传递(并在使用后立即销毁 – 有关详细信息,请参阅Spring参考手册)。 这有两个好处:

  • 它们在URL中不可见
  • 您不限于String,但可以传递任意对象。

你需要在这里小心,因为我认为你想要做什么并不是有充分理由支持的。 “redirect”指令将向您的控制器发出GET请求。 GET请求应该只使用请求参数检索现有状态,这是方法契约。 该GET请求不应该依赖于先前的交互,也不应该依赖于存储在会话中的某些对象的任何对象。 GET请求旨在检索现有(持久)状态。 您的原始( POST )请求应该保留您需要的所有内容GET请求以检索状态。

在这种情况下, RedirectAttributes不是为了支持你,即使你设法正确使用它,它只会工作一次然后它们将被销毁。 如果您随后刷新浏览器,则会出现应用程序错误,因为它无法再找到您的属性。

使用重定向发送的所有对象都可以从控制器传递到URL本身 –

 String message = "Hi Hello etc etc" return new ModelAndView("redirect:" + "welcome", "message", message); 

此消息变量将在URL中作为GET请求提供 –

 http://localhost:8080/Demo/welcome?message=Hi Hello etc etc 

您现在可以通过Scriptlet访问JSP上的变量 –

 <%= request.getParameter("message") %>