gpt4 book ai didi

java - 没有参数的Spring MVC重定向

转载 作者:行者123 更新时间:2023-11-29 04:34:55 24 4
gpt4 key购买 nike

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView loginPage(@Valid @ModelAttribute("user")User user, BindingResult result, ModelMap model) {

if(result.hasErrors()){
model.addAttribute("failedLogin", "username or password is invalid");
}

if(loginService.authenticateUser(user.getUsername(), user.getPassword())){
model.addAttribute("username", user.getUsername());
return new ModelAndView("redirect:/welcome");
}
else{
return new ModelAndView("login/login");
}
}

@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String welcomePage(@Valid @ModelAttribute("user")User user, BindingResult result, ModelMap model){
model.addAttribute("username", user.getUsername());
return "login/welcome";
}

当我登录时,我得到 ' http://localhost:8080/SpringMVC/welcome?username=volkansahin ' 等待 ' http://localhost:8080/SpringMVC/welcome '

我无法清理模型,但我在 JSP 文件中使用了用户名参数。

最佳答案

为了在重定向期间保留您的属性,您必须使用 RedirectAttributes

像这样:

@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String welcomePage(@Valid @ModelAttribute("user")User user, BindingResult result, ModelMap model, **final RedirectAttributes redirectAttributes**){
redirectAttributes.addFlashAttribute("username", user.getUsername());
return "login/welcome";
}

有关重定向属性的更多信息,请参阅此网址: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html

或者按照这个简单的例子:

http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/redirect-attributes/

关于java - 没有参数的Spring MVC重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42066087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com