0

Доброго времени суток. У меня возникла проблема при реализации изменения данных в моём веб приложении. Код: class UserController

 @RestController
@RequestMapping(value = "/users")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView getAll(){
        ModelAndView mov = new ModelAndView("main");
        mov.addObject("users", userService.getAllUsers());
        return mov;
    }

    @RequestMapping(value = "/addUser", method = RequestMethod.GET)
    public ModelAndView addView(){
        ModelAndView mov = new ModelAndView("add");
        mov.addObject("user",  new User());
        return mov;
    }

    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    public ModelAndView getUser(@PathVariable(value = "userId") Integer userId){
        ModelAndView mov = new ModelAndView("update");
        mov.addObject("user", userService.getUserById(userId));
        return mov;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ModelAndView addNewUser(@ModelAttribute("user") User user, BindingResult result){
        userService.addUser(user);
        return new ModelAndView(new RedirectView("/users"));
    }

    @RequestMapping(value = "/delete/{userId}")
    public ModelAndView delUser(@PathVariable("userId") Integer userId){
        userService.deleteUser(userId);
        return new ModelAndView(new RedirectView("/users"));
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public ModelAndView updUser(@ModelAttribute("user") User user){
        userService.updateUser(user);
        return new ModelAndView(new RedirectView("/users"));
    }



}

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <display-name>UserControl</display-name>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

application-context.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <tx:annotation-driven/>
    <context:component-scan base-package="com.malashenko.usercontrol.*"/>
    <jpa:repositories base-package="com.malashenko.usercontrol.repository"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/users?createDatabaseIfNotExist=true"/>
        <property name="username" value="root"/>
        <property name="password" value="1"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>

    <bean id="hibernateExceptionTranslator" class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
        <!-- Set JPA properties -->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <!--<prop key="javax.persistence.schema-generation.database.action">none</prop>-->
                <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <!-- Set base package of your entities -->
        <property name="packagesToScan" value="com.malashenko.usercontrol.*"/>
    </bean>

    <bean id="springLiquibaseBean" class="liquibase.integration.spring.SpringLiquibase">
        <property name="dataSource" ref="dataSource"/>
        <property name="changeLog" value="classpath:liquibase/usercontrol-liquibase.xml"/>
    </bean>

</beans>

main.jsp

 <%@ page language="java" contentType="text/html; charset=utf8"
         pageEncoding="utf8"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Панель пользователей</title>
    <script type="text/javascript" c:url value="resources/js/jquery.min.js"></script>
    <script type="text/javascript" c:url value="resources/js/bootstrap.min.js"></script>
    <script type="text/javascript" c:url value="resources/js/main.js"></script>

    <style>
        <%@include file='resources/css/bootstrap.min.css' %>
        <%@include file='resources/css/main.css' %>
        <%@include file='resources/css/jquery-ui.css' %>
        <%@include file='resources/css/jquery-ui.structure.css' %>
        <%@include file='resources/css/jquery-ui.theme.css' %>
    </style>
</head>
<body>
    <div class="tableUsers">
        <table class="table table-condensed">
            <tr>
                <td><input id="add" name="add" type="button"  value="+"
                               onclick="javascript:window.location='/users/addUser'"></th></td>
                <td>Фамилия</td>
                <td>Логин</td>
                <td>Пароль</td>
                <td>О себе</td>
                <td>Адрес</td>
            </tr>
            <c:forEach items="${users}" var="user">
                <tr>
                    <td>
                        <input id="del" name="delete" type="button"  value=" "
                                    onclick="javascript:window.location='/users/delete/'+ '${user.id}'">
                        <input id="upd" name="update" type="button"  value=" "
                               onclick="javascript:window.location='/users/'+ '${user.id}'">
                    </td>
                    <td>${user.surname}</td>
                    <td>${user.login}</td>
                    <td>${user.password}</td>
                    <td>${user.info}</td>
                    <td>${user.address}</td>
                </tr>
            </c:forEach>
        </table>
    </div>

</body>
</html>

update.jsp

    <%@ page language="java" contentType="text/html; charset=utf8"
         pageEncoding="utf8" %>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page isErrorPage="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Панель пользователей</title>
    <script type="text/javascript" c:url value="resources/js/jquery.min.js"></script>
    <script type="text/javascript" c:url value="resources/js/bootstrap.min.js"></script>
    <script type="text/javascript" c:url value="resources/js/main.js"></script>
    <script type="text/javascript" c:url value="resources/js/localization.js"></script>

    <style>
        <%@include file='resources/css/bootstrap.min.css' %>
        <%@include file='resources/css/main.css' %>
        <%@include file='resources/css/jquery-ui.css' %>
        <%@include file='resources/css/jquery-ui.structure.css' %>
        <%@include file='resources/css/jquery-ui.theme.css' %>
    </style>
</head>
<body>
<form:form method="post" action="/users/update" commandName="user">
    <table>
        <tr>
            <td><form:label path="surname">
                <spring:message text="Фамилия"/>
            </form:label></td>
            <td><form:input path="surname" value='${user.surname}'/></td>
        </tr>
        <tr>
            <td><form:label path="login">
                <spring:message text="Логин"/>
            </form:label></td>
            <td><form:input path="login" value='${user.login}'/></td>
        </tr>
        <tr>
            <td><form:label path="password">
                <spring:message text="Пароль"/>
            </form:label></td>
            <td><form:input path="password" value='${user.password}'/></td>
        </tr>
        <tr>
            <td><form:label path="info">
                <spring:message text="О себе"/>
            </form:label></td>
            <td><form:input path="info" value='${user.info}'/></td>
        </tr>
        <tr>
            <td><form:label path="address">
                <spring:message text="Адрес"/>
            </form:label></td>
            <td><form:input path="address" value='${user.address}'/></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit"
                                   value="<spring:message text="Изменить"/>"/></td>
        </tr>
    </table>
</form:form>
</body>
</html>

Я передаю свой объект из main.jsp в update. Потом я меня информацию и мне надо его обновить. Выскакивает ошибка томката

HTTP Status 405 – Method Not Allowed

Type Status Report

Message Request method 'POST' not supported

Description The method received in the request-line is known by the origin server but not supported by the target resource.

Apache Tomcat/8.5.23

Помогите плиз справиться с этой бедой

1 ответ 1

1

вы передаете методом POST

<form:form method="post" action="/users/update" commandName="user">

а на принимающей стороне (контроллере) есть инструкции только для метода PUT

@RequestMapping(value = "/update", method = RequestMethod.PUT)
public ModelAndView updUser(@ModelAttribute("user") User user){
    userService.updateUser(user);
    return new ModelAndView(new RedirectView("/users"));
}

определитесь какой метод хотите использовать. Об этом же вам сказал томкат

Message Request method 'POST' not supported - Сообщения с методом POST не поддерживаются

5
  • в jsp я не могу выбрать метод PUT к сожалению
    – Night Wolf
    17 ноя 2017 в 14:49
  • @NightWolf почему? и как вы тогда собираетесь отправлять запрос POST а слушать PUT ? 17 ноя 2017 в 14:51
  • @Kirill Stoianov я написал put в jsp, таже ошибка. Не видит jsp такого метода
    – Night Wolf
    17 ноя 2017 в 14:53
  • 3
    Вы и не сможете отправлять другими методами кроме как POST,GET из формы. Тут 2 решения. 1 Изменить метод на один из выше упомянутых. 2 Отправлять данные через ajax request. 17 ноя 2017 в 14:54
  • @GVArt можно ещё использовать HiddenHttpMethodFilter 23 ноя 2017 в 9:52

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.