gpt4 book ai didi

java - Spring MVC 中 POST 方法后重定向

转载 作者:行者123 更新时间:2023-12-02 10:52:38 31 4
gpt4 key购买 nike

我的问题是我想重定向到索引页,而不必查看 URL 中附加的属性。

我发现解决方案是 addFlashAttributes,它不会在 URL 中附加属性,但我看不到此方法保存的任何消息。

代码:

Controller

@RequestMapping(value="/login",method = RequestMethod.POST)  
public ModelAndView loginResult(HttpServletRequest req,
HttpServletResponse res,
RedirectAttributes redir) {
if (uname.equals(inf.getUsername()) & &pwd.equals(inf.getPassword()) && dept.equals(inf.getDept()))
{
req.getSession().setAttribute("uname",inf.getName());
return new ModelAndView("employeeLoginResult", "message", message1);
}
else if (uname.equals(inf2.getUsername()) && pwd.equals(inf2.getPassword()) && dept.equals(inf2.getDept()))
{
req.getSession().setAttribute("uname", inf2.getName());
return new ModelAndView("adminLoginResult", "message", message2);
}
else
{
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:/index.jsp");
redir.addFlashAttribute("message","Sorry Username Password Error");
return modelAndView;
}
}

现在我已经硬编码了验证值,并且将来会将验证与数据库的 DAO 层集成。 addFlashAttribute 为我完成了不将消息附加到 URL 的工作,但我还想在索引页上显示该消息。

索引页

<head><tile>index</title>
</head>
<body>
<b><span class="heading">LOGIN USER</span></b>
<div class="container">
<form action="login.html" method="Post">
<div class="form_style">
<input type="text" name="username" placeholder="Enter Username"/>
<input type="password" name="pwd" placeholder="Enter password"/>
<select name="dept">
<option>IT</option>
<option>Admin</option>
<option>HR</option>
<option>Marketing</option>
</select>
<input type="Submit" value="submit">
<p>${message}</p>
</div>
</form>
</div>
</body>

我做错了什么?谁能解释一下吗?

为什么${message}不显示该属性?

感谢任何帮助。谢谢你同样的。

最佳答案

您可以如下更改 Controller 并使用相同的index.jsp文件。

Controller

@RequestMapping(value="/login",method = RequestMethod.POST)  
public ModelAndView loginResult(HttpServletRequest req,HttpServletResponse res, Model model){

String message = "";
String response = "";

if(uname.equals(inf.getUsername())&&pwd.equals(inf.getPassword())&&dept.equals(inf.getDept())) {
req.getSession().setAttribute("uname",inf.getName());
message = message1;
response = "employeeLoginResult";
}
else if(uname.equals(inf2.getUsername())&&pwd.equals(inf2.getPassword())&&dept.equals(inf2.getDept())) {
req.getSession().setAttribute("uname",inf2.getName());
message = message2;
response = "adminLoginResult";
}
else{
message = "Sorry Username Password Error";
response = "index";
}
model.addAttribute("message", message);
return response;
}

关于java - Spring MVC 中 POST 方法后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52050017/

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