问题描述
我的目标是在重定向期间将模型属性从控制器传递到 JSP 页面,并避免该属性显示在 URL 中.下面的源代码使用 java 数据对象验证来自数据存储的登录.
My objective is to pass model attributes from controller to JSP page during a redirect and avoid the attribute being displayed in URL. The source code below is validating login from datastore using java data objects.
控制器:
@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.
My current URL is /welcome?USERNAME=robin
My goal is to display it as /welcome
Also, my page is supposed to display "Welcome robin" whereas it displays only Welcome.
推荐答案
RedirectAttributes 只适用于 RedirectView,请同理
RedirectAttributes only work with RedirectView, please follow the same
@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 参考手册).这有两个利益:
Those flash attributes are passed via the session (and are destroyed immediately after being used - see Spring Reference Manual for details). This has two interests :
- 它们在 URL 中不可见
- 您不仅限于字符串,还可以传递任意对象.
这篇关于在 Spring MVC 中重定向期间传递模型属性并在 URL 中避免相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!