Подтвердить что ты не робот

Spring Контроллер 404 перенастроен после использования метода POST.

У меня есть контроллер Spring, который вызывается из JQuery.post(). Когда он вызывается, метод контроллера вызывается и возвращается. Но затем, в фоновом режиме, Spring изменяет URL-адрес и вызывает прирост сервера. Сервер отвечает 404.

Я думаю, что это ответ на Spring, пытаясь найти представление после того, как был обработан метод POST.

Как остановить контроллер Spring от этого.

Вот мой контроллер Spring:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/person")
public class DataController {

  private List<Person> people = new ArrayList<Person>();

  @RequestMapping(value="put", method = RequestMethod.POST)
  public void addPerson(@ModelAttribute("person") Person person){
    System.out.println(">>>>>>> person: " + person);
    System.out.println(">>>>>>>>> " + person.getFirstName());
    people.add(person);
  }
}

Вот мой 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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="uk.co.jeeni" />

    <mvc:annotation-driven />

</beans>

Вот мой файл web.xml:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:applicationContext-web.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/data/*</url-pattern>
    </servlet-mapping>
</web-app>

Вот мой вызов JQuery из моего HTML файла:

function attachSendDataEvent(){
    $("#sendData").click(function(){

        var data = "firstName=" + $("#firstName").val() + "&" +
                "lastName=" + $("#lastName").val() + "&" +
                "address=" + $("#address").val() + "&" +
                "postcode=" + $("#postcode").val();

        $.post("data/person/put",
                data,
                dataSentOK
        );
    });

    return false;
}

Функция dataSentOK выполняет только alert("DONE").

Поэтому, когда метод JQuery вызывает URL-адрес:

http://localhost:8080/jquery/data/person/put

а на стороне сервера метод System.out.println(...) распечатает данные, как ожидалось.

Однако в Firebug сервер отправляет обратно 404.

Итак, я включил ведение журнала с помощью Spring и получил следующее:

[01] DispatcherServlet [DEBUG] DispatcherServlet with name 'dispatcherServlet' processing POST request for [/jquery/data/person/put]
[02] AbstractHandlerMethodMapping [DEBUG] Looking up handler method for path /person/put
[03] AbstractHandlerMethodMapping [DEBUG] Returning handler method [public void uk.co.jeeni.DataController.addPerson(uk.co.jeeni.Person)]
[04] AbstractBeanFactory [DEBUG] Returning cached instance of singleton bean 'dataController'
[05] DispatcherServlet [DEBUG] Rendering view [org.springframework.web.servlet.view.InternalResourceView: name 'person/put'; URL [person/put]] in DispatcherServlet with name 'dispatcherServlet'
[06] AbstractView [DEBUG] Added model object 'org.springframework.validation.BindingResult.person' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'person/put'
[07] AbstractView [DEBUG] Added model object 'person' of type [uk.co.jeeni.Person] to request in view with name 'person/put'
[08] InternalResourceView [DEBUG] Forwarding to resource [person/put] in InternalResourceView 'person/put'
[09] DispatcherServlet [DEBUG] DispatcherServlet with name 'dispatcherServlet' processing POST request for [/jquery/data/person/person/put]
[10] AbstractHandlerMethodMapping [DEBUG] Looking up handler method for path /person/person/put
[11] AbstractHandlerMethodMapping [DEBUG] Did not find handler method for [/person/person/put]
[12] DispatcherServlet [ WARN] No mapping found for HTTP request with URI [/jquery/data/person/person/put] in DispatcherServlet with name 'dispatcherServlet'
[13] FrameworkServlet [DEBUG] Successfully completed request
[14] FrameworkServlet [DEBUG] Successfully completed request

В ответ на запрос POST URL (/jquery/data/person/put) правильный метод найден и вызывается (строки с 1 по 7), но затем Spring переходит к InternalResourceView в строке 8, который изменяет URL-адрес на /jquery/data/person/person/put, и это невозможно найти.

Как остановить Spring от попытки найти представление вообще. Все, что я хочу сделать, это вернуть чистоту и сделать.

Спасибо за вашу помощь.

4b9b3361

Ответ 1

решаемые.

Проблема заключалась в том, что предлагался #CodeChimp, за исключением того, что мне все еще нужен тип возврата void.

Я добавил метод @ResponseBody в метод addPerson, и все работало нормально:

@RequestMapping(value="put", method = RequestMethod.POST)
**@ResponseBody**
public void addPerson(@ModelAttribute("person") Person person){
  System.out.println(">>>>>>> person: " + person);
  System.out.println(">>>>>>>>> " + person.getFirstName());
  people.add(person);
}

Ключ появился из http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody. Хотя в документации не ясно, что происходит с возвратом void. Просто попробовал, и это сработало.

Ответ 2

Я считаю, что если у вас есть возвращаемый тип null или void, Spring попытается разрешить представление на основе URL-адреса запроса. Я думаю, что правильная форма здесь состояла бы в том, чтобы просто вернуть страницу OK, так как это не похоже на JSON или что-то в этом роде. Или просто пометьте его @ResponseBody и верните пустую строку.