JQuery, Spring MVC @RequestBody i JSON-dzięki czemu działają razem

Chciałbym mieć dwukierunkową serializację JSON do Javy

Używam pomyślnie Java do JSON do ścieżki JQuery... (@ResponseBody) np.

@RequestMapping(value={"/fooBar/{id}"}, method=RequestMethod.GET)
     public @ResponseBody FooBar getFooBar(
            @PathVariable String id,
            HttpServletResponse response , ModelMap model) {
        response.setContentType("application/json");
...
}

A w JQuery używam

$.getJSON('fooBar/1', function(data) {
    //do something
});

To działa dobrze (np. adnotacje już działają, dzięki wszystkim odpowiedziającym)

Jak jednak wykonać odwrotną ścieżkę: czy JSON zostanie serializowany do obiektu Java przy użyciu RequestBody?

Bez względu na to, co próbuję, nie mogę dostać czegoś takiego jak to działa:

@RequestMapping(value={"/fooBar/save"}, method=RequestMethod.POST)
public String saveFooBar(@RequestBody FooBar fooBar,
        HttpServletResponse response , ModelMap model) {

  //This method is never called. (it does when I remove the RequestBody...)
}

Mam poprawnie skonfigurowany (serializuje się po wyjściu) i mam MVC ustawione jako adnotacje oczywiście

Jak to zrobić? czy to w ogóle możliwe? a może Spring / JSON / JQuery jest oneway (out)?


Update:

Zmieniłem ustawienie Jacksona

<bean id="jsonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

<!-- Bind the return value of the Rest service to the ResponseBody. -->
<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <util:list id="beanList">
            <ref bean="jsonHttpMessageConverter" />
<!--            <ref bean="xmlMessageConverter" /> -->              
        </util:list>
    </property>
</bean>

Do (prawie podobnego) sugerowanego

<bean id="jacksonMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter" />
            </list>
        </property>
    </bean> 

I wydaje się działać! Nie wiem, co to za sztuczka, ale działa...

Author: Eran Medan, 2011-05-06

5 answers

Jestem prawie pewien, że wystarczy się zarejestrować MappingJacksonHttpMessageConverter

(najłatwiej to zrobić jest poprzez <mvc:annotation-driven /> W XML lub @EnableWebMvc W Java)

Zobacz:


Oto przykład pracy:

Maven POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version><name>json test</name>
    <dependencies>
        <dependency><!-- spring mvc -->
            <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
        </dependency>
        <dependency><!-- jackson -->
            <groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
        </dependency>
    </dependencies>
    <build><plugins>
            <!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
            <!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
            <version>7.4.0.v20110414</version></plugin>
    </plugins></build>
</project>

W folderze src / main / webapp / WEB-INF

Www.xml

<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>json</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>json</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

Json-servlet.xml

<beans xmlns="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.xsd">

    <import resource="classpath:mvc-context.xml" />

</beans>

W folderze src / main / resources:

Mvc-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">

    <mvc:annotation-driven />
    <context:component-scan base-package="test.json" />
</beans>

W folderze src/main/java/test / json

TestController.java

@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(method = RequestMethod.POST, value = "math")
    @ResponseBody
    public Result math(@RequestBody final Request request) {
        final Result result = new Result();
        result.setAddition(request.getLeft() + request.getRight());
        result.setSubtraction(request.getLeft() - request.getRight());
        result.setMultiplication(request.getLeft() * request.getRight());
        return result;
    }

}

Prośba.java

public class Request implements Serializable {
    private static final long serialVersionUID = 1513207428686438208L;
    private int left;
    private int right;
    public int getLeft() {return left;}
    public void setLeft(int left) {this.left = left;}
    public int getRight() {return right;}
    public void setRight(int right) {this.right = right;}
}

Wynik.java

public class Result implements Serializable {
    private static final long serialVersionUID = -5054749880960511861L;
    private int addition;
    private int subtraction;
    private int multiplication;

    public int getAddition() { return addition; }
    public void setAddition(int addition) { this.addition = addition; }
    public int getSubtraction() { return subtraction; }
    public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
    public int getMultiplication() { return multiplication; }
    public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}

Możesz przetestować tę konfigurację wykonując mvn jetty:run na w wierszu poleceń, a następnie wysłanie żądania POST:

URL:        http://localhost:8080/test/math
mime type:  application/json
post body:  { "left": 13 , "right" : 7 }

Użyłem Poster Firefox plugin aby to zrobić.

Oto jak wygląda odpowiedź:

{"addition":20,"subtraction":6,"multiplication":91}
 96
Author: Sean Patrick Floyd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-26 09:13:41

Ponadto musisz również mieć pewność, że masz

 <context:annotation-config/> 

W konfiguracji SPring XML.

Polecam również przeczytać ten wpis na blogu. Bardzo mi to pomogło. Spring blog-Ajax w Spring 3.0

Update:

Właśnie sprawdziłem mój kod roboczy, gdzie mam @RequestBody działa poprawnie. Ja też mam tą fasolkę w moim config:

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
  <list>
    <ref bean="jacksonMessageConverter"/>
  </list>
</property>
</bean>
Może byłoby miło zobaczyć, co mówi. zwykle daje więcej informacje i z mojego doświadczenia @RequestBody nie powiedzie się, jeśli typ treści twojego żądania nie jest Application/JSON. Możesz uruchomić Fiddler 2, aby go przetestować, a nawet Wtyczka Mozilla Live HTTP headers może pomóc.
 12
Author: danny.lesnik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-24 18:47:42

Oprócz odpowiedzi tutaj...

Jeśli używasz jquery po stronie klienta, to działało dla mnie:

Java:

@RequestMapping(value = "/ajax/search/sync") 
public String sync(@RequestBody Foo json) {

Jquery (musisz dołączyć json2.js mieć JSON.funkcja stringify):

$.ajax({
    type: "post",
    url: "sync", //your valid url
    contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
    data: JSON.stringify(jsonobject), //json object or array of json objects
    success: function(result) {
        //do nothing
    },
    error: function(){
        alert('failure');
    }
});
 8
Author: rafael lean ansay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-12 13:58:47

Jeśli nie chcesz samodzielnie konfigurować konwerterów wiadomości, możesz użyć albo @EnableWebMvc lub , Dodaj Jacksona do ścieżki klas, a Spring da ci domyślnie zarówno JSON, XML( i kilka innych konwerterów). Dodatkowo otrzymasz inne powszechnie używane funkcje konwersji, formatowania i walidacji.

 5
Author: matsev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-10 20:04:59

Jeśli chcesz używać Curl do połączeń z JSON 2 i Spring 3.2.0 w hand checkout FAQ tutaj . Jako Adnotationmethodhandleradapter jest przestarzały i zastąpiony przez RequestMappingHandlerAdapter.

 0
Author: AmirHd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:41