2011-01-15 3 views
4

J'essaie d'apprendre le printemps MVC, jusqu'ici tout va bien, mais je suis coincé maintenant. J'essaie d'apprendre comment créer json et l'obtenir avec javascript (jquery). Mais à des fins de test, j'ai essayé de créer quelque chose juste pour que je puisse voir ce qui est affiché correctement par requête http, alors je vais essayer de créer json et l'obtenir, mais jusqu'à présent, je ne peux même pas demander travail. Voici mon contrôleur:Numéro de contrôleur mvc printemps

@Controller 
@RequestMapping(value="/") 
public class IndexController { 

@RequestMapping(method=RequestMethod.GET) 
    public String index() { 
      return "index"; 
    } 

Map<Long,Item> itemMap = createItemMap(); 

@RequestMapping(value="item/{itemId}", method=RequestMethod.GET) 
    public @ResponseBody Item get(@PathVariable Long itemId) { 
     Item item = itemMap.get(itemId); 
     if (status == null) { 
      throw new ResourceNotFoundException(itemId); 
     } 
     return item; 
    } 

private Map<Long,Item> createItemMap(){ 
//omitted because its irrelevant 
//I created 2 item objects , with id 1 and 2 for testing purposes 
} 

} 

Ceci est le contenu de mon servlet-context.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:beans="http://www.springframework.org/schema/beans" 
    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"> 

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 

    <!-- Enables the Spring MVC @Controller programming model --> 
    <annotation-driven /> 

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> 
    <resources mapping="/resources/**" location="/resources/" /> 

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> 
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <beans:property name="prefix" value="/WEB-INF/views/" /> 
     <beans:property name="suffix" value=".jsp" /> 
    </beans:bean> 

    <!-- Imports user-defined @Controller beans that process client requests --> 
    <beans:import resource="controllers.xml" /> 

</beans:beans> 

Et controllers.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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <!-- Scans within the base package of the application for @Components to configure as beans --> 
    <context:component-scan base-package="com.testing.mvc.controller" /> 

     <!-- Application Message Bundle --> 
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
     <property name="basename" value="/WEB-INF/messages/messages" /> 
     <property name="cacheSeconds" value="0" /> 
    </bean> 

</beans> 

Ma guerre est appelée Test.war, quand j'essaye localhost:8080/Test j'obtiens l'affichage d'index qui est OK. Mais peu importe ce que je tente:

localhost:8080/Test/item/1 
localhost:8080/Test/item?itemId=1 
localhost:8080/item?itemId=1 

je me retrouve avec une sorte d'erreur, le plus intéressant est celui-ci:

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers(). 

J'ai googlé beaucoup trouvé à ce intéressant:

http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/ https://src.springframework.org/svn/spring-samples/mvc-ajax/trunk/ Mapping restful ajax requests to spring Spring's Json not being resolved with appropriate response

Rien n'a aidé jusqu'à présent, aucune idée de ce qui me manque. Désolé de fournir trop d'informations.

Répondre

2

Pour autant que je peux vous dire ce manque résolveur comme celui-ci dans votre répartiteur Serlet:

<bean name="jsonViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver"> 
    <property name="order" value="1"/> 
</bean> 

Prenez oeil à ceci:
http://spring-json.sourceforge.net/quick_simpleform.html

Vous devez créer un fichier dans views.xml yoru WEB-INF direcotry avec ce contenu:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
     "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> 
<beans> 
    <bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView"/> 
</beans> 
+0

@Mat Banik, merci pour votre réponse. Maintenant, je reçois différent type d'exception 'org.springframework.beans.factory.BeanCreationException: Erreur lors de la création du bean avec le nom 'jsonViewResolver' défini dans la ressource ServletContext [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation de la méthode init a échoué; l'exception imbriquée est org.springframework.beans.factory.BeanDefinitionStoreException: IOException analyse le document XML à partir de la ressource ServletContext [/WEB-INF/views.xml]; l'exception imbriquée est java.io.FileNotFoundException: Impossible d'ouvrir la ressource ServletContext [/WEB-INF/views.xml] ' – London

+0

@Mat Banik Merci de votre mise à jour, désolé d'être stupide, j'ai nommé un fichier view.xml au lieu de vues .xml. J'ai également trouvé un moyen d'arround entre temps, j'ai trouvé com.google.Gson lib. Ainsi, au lieu de renvoyer l'élément, j'ai changé le type de retour de la méthode en String et j'ai converti l'item en string avec cette lib, et j'ai eu json dans ma page. lequel est préférable d'utiliser? – London

+0

@Mat Banik merci – London