Статус HTTP 405 - Метод запроса "POST" не поддерживается в Spring MVC

Я создал приложение spring mvc, используя шаблон freemarker в качестве части представления. В этом попытался добавить модель с использованием forms.I также использовать spring безопасности Вот код

employee.ftl

<fieldset>
    <legend>Add Employee</legend>
  <form name="employee" action="addEmployee" method="post">
    Firstname: <input type="text" name="name" /> <br/>
    Employee Code: <input type="text" name="employeeCode" />   <br/>
    <input type="submit" value="   Save   " />
  </form>

employeeController.java

@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
    public String addEmployee(@ModelAttribute("employee") Employee employee) {
        employeeService.add(employee);
        return "employee";
    }

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<!-- Spring MVC -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/appServlet/servlet-context.xml,
            /WEB-INF/spring/springsecurity-servlet.xml
        </param-value>
    </context-param>

    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


</web-app>

Spring -security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http security="none" pattern="/resources/**"/>
    <!-- enable use-expressions -->
    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/login" access="isAnonymous()"/>
        <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')" />

        <!-- access denied page -->
        <access-denied-handler error-page="/403" />
        <form-login 
            login-page="/login" 
            default-target-url="/"
            authentication-failure-url="/login?error" 
            username-parameter="username"
            password-parameter="password" />
        <logout logout-success-url="/login?logout" />
        <!-- enable csrf protection -->
        <csrf />
    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService" >
            <password-encoder hash="bcrypt" />    
        </authentication-provider>
    </authentication-manager>

</beans:beans>

При нажатии кнопки отправки возвращается ошибка `

Состояние HTTP 405 - Не поддерживается метод запроса POST.

` Я дал метод POST как на ftl, так и на контроллере. Тогда почему это произойдет?

Ответы

Ответ 1

Я не уверен, что это помогает, но у меня была та же проблема.

Вы используете SpringSecurityFilterChain с защитой CSRF. Это означает, что вам нужно отправить токен при отправке формы через запрос POST. Попробуйте добавить следующий вход в форму:

<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>

Ответ 2

Насколько я понял, упомянутые решения не работали для последней версии SpringSecurity. Вместо того чтобы проходить со скрытым, вы также можете отправить его через URL-адрес действия, как показано ниже:

<form method="post" action="doUpload?${_csrf.parameterName}=${_csrf.token}" enctype="multipart/form-data">

Ответ 3

Я нашел решение. Это связано с защитой защиты от перекрестных запросов безопасности (CSRF) spring. Он блокирует URL. Поэтому я добавил дополнительное поле внутри формы.

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

Теперь он работает правильно.

Ответ 4

Попробуйте заменить:

action="addEmployee"

с:

action="${pageContext.request.contextPath}/addEmployee"

Если вы не используете Spring 3.2

ИЗМЕНИТЬ после просмотра XML:

Попробуйте переместить файл servlet-context.xml в каталог WEB-INF и переименуйте его в appServlet-context.xml. Затем удалите строку:

/WEB-INF/spring/appServlet/servlet-context.xml,

Из контекстаConfigLocation в вашем web.xml.

Согласие заключается в том, что контекстный XML файл имеет имя "[сервлет-имя] -контекст .xml", где [имя сервлета] является именем DispatcherServlet.

Также попробуйте добавить '/' к вашему действию формы, поэтому:

action="/addEmployee"

Ответ 5

Это работает для меня:

.and().csrf().disable();

другое решение (но каждая форма)

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>