JQuery, Spring MVC @RequestBody et JSON-making it work together
j'aimerais avoir une sérialisation JSON bidirectionnelle à Java
j'utilise avec succès le chemin Java-JSON-JQuery... ( @ResponseBody
)
par exemple
@RequestMapping(value={"/fooBar/{id}"}, method=RequestMethod.GET)
public @ResponseBody FooBar getFooBar(
@PathVariable String id,
HttpServletResponse response , ModelMap model) {
response.setContentType("application/json");
...
}
et dans JQuery j'utilise
$.getJSON('fooBar/1', function(data) {
//do something
});
cela fonctionne bien (par ex. travaux d'annotations déjà, merci à tous les answerers)
Cependant, comment puis-je faire de la inverse chemin: est-ce que JSON a été sérialisé vers un objet Java en arrière en utilisant RequestBody?
peu importe ce que j'essaie, Je ne peux pas obtenir quelque chose comme ça pour fonctionner:
@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...)
}
J'ai Jackson configuré correctement (il sérialise sur la sortie) et j'ai MVC défini comme annotations pilotées bien sûr
Comment faire pour que ça marche? est-il possible? ou Spring / JSON / JQuery is oneway (out)?
mise à Jour:
j'ai changé cette Jackson paramètre
<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>
à la (presque similaire) suggéré
<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>
et ça a l'air de marcher! Je ne sais pas ce que fait exactement le truc, mais ça fonctionne...
5 réponses
je suis sûr que vous n'avez qu'à vous inscrire MappingJacksonHttpMessageConverter
(la façon la plus facile de faire que est par <mvc:annotation-driven />
en XML ou @EnableWebMvc
en Java )
voir:
voici un exemple pratique:
POM Maven
<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>
dans le dossier src / main/webapp / WEB-INF
web.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>
in src folder / main/ resources:
mvc-contexte.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>
dans le dossier 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;
}
}
demande.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;}
}
résultat.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; }
}
vous pouvez tester cette configuration en exécutant mvn jetty:run
sur la ligne de commande, puis en envoyant une demande de poste:
URL: http://localhost:8080/test/math
mime type: application/json
post body: { "left": 13 , "right" : 7 }
j'ai utilisé le Poster plugin Firefox pour faire ceci.
voici à quoi ressemble la réponse:
{"addition":20,"subtraction":6,"multiplication":91}
en outre, vous devez également être sûr que vous avez""
<context:annotation-config/>
dans votre configuration de printemps xml.
je vous recommande aussi de lire ce billet de blog. Il m'a beaucoup aidé. Printemps blog - Ajax Simplifications au Printemps 3.0
mise à jour:
vient de vérifier mon code de travail où @RequestBody
fonctionne correctement.
J'ai aussi ce haricot dans ma 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>
peut-être serait-il agréable de voir ce que Log4j
dit. il donne habituellement plus d'informations et d'après mon expérience le @RequestBody
échouera si le type de contenu de votre demande n'est pas Application/JSON
. Vous pouvez lancer Fiddler 2 pour le tester, ou même le plugin Mozilla Live HTTP headers peut vous aider.
en plus des réponses ici...
si vous utilisez jquery côté client, cela a fonctionné pour moi:
Java:
@RequestMapping(value = "/ajax/search/sync")
public String sync(@RequestBody Foo json) {
Jquery (vous devez inclure Douglas Crockford de json2.js pour avoir le JSON.fonction 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');
}
});
si vous ne voulez pas configurer vous-même les convertisseurs de messages, Vous pouvez utiliser l'une des options suivantes:
@Enablwebmvc ou