为什么model.put中的值附加在URL中

时间:2016-01-07 03:29:22

标签: spring jsp spring-mvc

我正在构建一个Spring MVC Web App。在一个Controller中,我使用了model.put方法将一些信息传递给jsp文件。

以下是控制器的片段

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<body>
<a href="/upload">Click to upload page</a>
</body>
</html>

index.jsp和login.jsp:

<%--
  Created by IntelliJ IDEA.
  User: cbl
  Date: 2016/1/6
  Time: 15:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
<h1>${message}</h1>

<form method = "POST" action = "/login">
    <label for="username">Username</label>
    <input id="username" type="text" name = "username">
    <label for="password">Password</label>
    <input id="password"type="password" name="password">
    <input type="submit" value="login">
</form>

</body>
</html>

http://localhost:8000/login?message=login+failed

$ {message}被展开以显示在body中,但是,它会在URl:http://localhost:8000/index?message=login+successful++和{{1}}之后附加

感谢任何回复

1 个答案:

答案 0 :(得分:0)

由于您要返回重定向,因此会在封面下创建新的GET请求,这就是为什么要附加到网址。

如果您只想将数据保留在模型中,可以将闪存范围与RedirectAttributes

一起使用
@RequestMapping(value = "/login" ,  method= RequestMethod.POST)
public String loginPost(HttpSession session,
                        RedirectAttributes ra,
                        @RequestParam(value = "username") String username, 
                        @RequestParam(value = "password") String password) throws Exception {
    User user = getUser(username, password);
    if(user !=null){
        session.setAttribute("username",username);
        ra.addFlashAttribute("message","login successful  ");
        return "redirect:/index";
    }else{
        ra.addFlashAttribute("message","login failed");
        return "redirect:/login";
    }
}