【问题标题】:Spring MVC is confusing get and post methods with the same request mappingSpring MVC 混淆了具有相同请求映射的 get 和 post 方法
【发布时间】:2015-05-26 04:46:20
【问题描述】:

我有一个登录控制器,我已将“/login”路径映射到两种不同的方法。将调用一个用于获取,另一个用于发布。

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model){
    LoginDto loginDto = new LoginDto();
    model.addAttribute("loginDto", loginDto);
    return "home/login";
}

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(@Valid LoginDto loginDto, BindingResult bindingResult){
    if(bindingResult.hasErrors()){
        return "home/login";
    }
    return "redirect:/";
}

我有百里香叶形式

<form method="POST" th:action="@{/login}" th:object="${loginDto}">
    <div class="form-group-row">
        <label> Email </label>
        <input type = "text" th:field = "*{email}"/>
        <span th:if="${#fields.hasErrors('email')}" th:errors = "*{email}"></span>
    </div>
    <div>
        <label> Password </label>
        <input type = "text" th:field = "*{password}"/>
    </div>
    <input type="submit" />
</form>

当输入数据并单击提交时,将调用带有 GET 请求的方法。我通过在这两种方法中插入断点来知道这一点。现在,该网址的末尾还有一个 ?errors 。我也将 url 映射更改为像这样“doLogin”的第二种方法

@RequestMapping(value = "/dologin", method = RequestMethod.POST)
public String doLogin(@Valid LoginDto loginDto, BindingResult bindingResult){
    if(bindingResult.hasErrors()){
        return "home/login";
    }
    return "redirect:/";
}

并将表单更改为此

<form method="POST" th:action="@{/dologin}" th:object="${loginDto}">
    <div class="form-group-row">
        <label> Email </label>
        <input type = "text" th:field = "*{email}"/>
        <span th:if="${#fields.hasErrors('email')}" th:errors = "*{email}"></span>
    </div>
    <div>
        <label> Password </label>
        <input type = "text" th:field = "*{password}"/>
    </div>
    <input type="submit" />
</form>

它有效。我可以输入数据并点击提交按钮,我在 doLogin 方法中。但是,我想保持 GET 和 POST 到同一个 url 的映射,以便根据请求方法做不同的事情。

此外,当我一开始创建表单时,我忘记指定一个 method="post" 并且在测试它时从这个表单提交了对“/login”的获取请求。也许这连接了一些需要取消连接的东西。

这是一个错误吗?我可以将具有不同请求方法的相同 url 映射到其他控制器方法,但这个似乎不想工作。有什么想法吗?

【问题讨论】:

  • 我不确定,但尝试在表单标签中使用“th:method”会起作用。
  • 刚刚在表单标签中尝试了“th:method”,它具有相同的行为。不过还是谢谢。

标签: spring-mvc spring-boot


【解决方案1】:

我想通了。映射到 POST 请求的方法的原因是因为我使用的是 spring security 并且它没有完全设置。 Spring Security 的登录页面也映射到 /login 并且附加了

localhost/login?error

到 url 字符串是 spring security 在登录过程出现错误时附加的内容。我还没有使用 Spring Security 设置身份验证,因此它认为存在错误。我将继续设置 Spring Security,但这就是我的 POST 请求未映射到 doLogin 方法的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多