【问题标题】:Spring MVC controller method called for GET but not for POSTSpring MVC 控制器方法调用 GET 但不调用 POST
【发布时间】:2019-09-02 15:12:54
【问题描述】:

尊敬的各位,我在Controller类中为URL“/persons/search”定义了两个方法。一种是使用 RequestMethod.Get,另一种是使用 RequestMethod.POST。带有 GET 请求的方法被调用,但带有 POST 请求的方法没有被调用。在浏览器中,当我加载 /persons/search 并发送 GET 请求时,视图返回成功。但是,当我填写搜索字段并按提交(生成 POST)时,我收到 404。我试图在方法中打印值以检查它是否被调用,但值不打印。该方法永远不会被调用。请注意,几天前它运行良好,同时我刚刚实施了 Spring Security,我认为这不应该造成任何伤害,但后来它不起作用。我已允许对 /persons/** 的所有请求。任何有关可能导致此问题的帮助将不胜感激。问候

控制器:

@RequestMapping(value = "/persons/search", method = RequestMethod.GET)
public String searchPersons(Model model) {
    logger.debug("searchPersons()");
    return "users/searchPersons";

}

@RequestMapping(value = "/persons/search", method = RequestMethod.POST)
public String listPersons(@RequestParam("searchString") String searchStr, Model model) {
    logger.debug("listPersons()");
    System.out.println("Entered search");
    userService.initialize();
    institutions = userService.getInstitutions();
    model.addAttribute("persons", userService.searchPersons(searchStr));
    System.out.println("completed search");
    return "users/listPersons";
}

查看:

<%@ page session="false"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<!DOCTYPE html>
<html lang="en">

<jsp:include page="../fragments/header.jsp" />

<body>

<div class="container">

    <c:if test="${not empty msg}">
        <div class="alert alert-${css} alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <strong>${msg}</strong>
        </div>
    </c:if>
    <h1>Search Persons</h1>

<!-- The form -->
    <spring:url value="/persons/search" var="searchPersonsActionUrl" />
    <form class="searchBar" action="${searchPersonsActionUrl}" method="POST">
      <input type="text" placeholder="Enter uid or fullname..." name="searchString">
      <button type="submit"><i class="fa fa-search"></i></button>
    </form>

</div>

<jsp:include page="../fragments/footer.jsp" />

</body>
</html>

浏览器的网络标签截图:

【问题讨论】:

  • 您没有显示您的 HTML 表单或浏览器“网络”选项卡的屏幕截图。
  • 您可以尝试使用邮递员或任何具有正确请求参数的其他客户端访问您的应用程序,并确认它是否正在访问您的帖子网址。
  • @chrylis 抱歉,现在添加
  • @SujayMohan 好的.. 现在尝试,将返回更新
  • @SujayMohan 用 postman 试过,结果一样,找不到 404 和浏览器一样返回 spring 错误页面

标签: java spring-mvc model-view-controller


【解决方案1】:

较新的 spring 安全版本默认启用 csrf,这有时会导致奇怪的错误。尝试在您的安全配置中通过.csrf().disable() 禁用或查看此处:https://www.baeldung.com/spring-security-csrf

【讨论】:

  • 哇,这就是问题所在,按照您的建议禁用 csrf 后它又开始工作了!非常感谢。你能帮忙解决csrf不允许它工作的可能原因吗?因为我认为应该修改应用程序以启用 csrf。你说什么?
  • 需要提供csrf token,看@chrylis 评论
猜你喜欢
  • 1970-01-01
  • 2014-11-30
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多