2016-06-22 1 views
2

enter image description hereDéployé HelloWorld simple avec application Spring MVC (sans web.xml) donne une erreur 404

Je suis novice à Spring MVC avec annotations, j'ai travaillé avec la configuration XML Spring MVC plus tôt. Je reçois erreur 404 lorsque j'essaie de frapper l'URL http://localhost:8080/HelloWorldApp. Je l'ai écrit trois classes: 1. AppIntializer 2. AppConfig 3. AppController Suite morceau de code:

package com.demo; 
     public class AppIntializer implements WebApplicationInitializer { 
      private static final String CONFIG_LOCATION = "com.demo.config"; 

      @Override 
      public void onStartup(ServletContext servletContext) throws ServletException { 

      System.out.println("Initializing Application for " + servletContext.getServerInfo()); 

      // Create ApplicationContext 
      AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); 
      applicationContext.setConfigLocation(CONFIG_LOCATION); 

      // Add the servlet mapping manually and make it initialize automatically 
      DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext); 
      ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet); 

      servlet.addMapping("/"); 
      servlet.setAsyncSupported(true); 
      servlet.setLoadOnStartup(1); 
     } 
    } 

    package com.demo.config; 
     @Configuration 
     @EnableWebMvc 
     @ComponentScan("com.demo") 
     public class AppConfig extends WebMvcConfigurerAdapter { 

     } 

    package com.demo.web.controller; 
    @Controller 
    public class AppController { 
     @ResponseBody 
     @RequestMapping(value = "/", method = RequestMethod.GET) 
     public String helloWorld() { 
      return "Hello World: Spring MVC without XML configuration"; 
     } 
    } 

pom.xml

<modelVersion>4.0.0</modelVersion> 
    <groupId>HelloWorldApp</groupId> 
    <artifactId>HelloWorldApp</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>war</packaging> 
    <properties> 
     <spring-framework.version>4.2.1.RELEASE</spring-framework.version> 
     <servlet.version>3.0.1</servlet.version> 

    </properties> 
    <dependencies> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-webmvc</artifactId> 
      <version>${spring-framework.version}</version> 
      <scope>provided</scope> 
     </dependency> 

     <dependency> 
      <groupId>javax.servlet</groupId> 
      <artifactId>javax.servlet-api</artifactId> 
      <version>${servlet.version}</version> 
      <scope>provided</scope> 
     </dependency> 
    </dependencies> 
    <build> 
     <sourceDirectory>src</sourceDirectory> 
     <plugins> 
      <plugin> 
       <artifactId>maven-war-plugin</artifactId> 
       <version>2.6</version> 
       <configuration> 
        <warSourceDirectory>WebContent</warSourceDirectory> 
        <failOnMissingWebXml>false</failOnMissingWebXml> 
       </configuration> 
      </plugin> 
      <plugin> 
       <artifactId>maven-compiler-plugin</artifactId> 
       <version>3.3</version> 
       <configuration> 
        <source>1.7</source> 
        <target>1.7</target> 
       </configuration> 
      </plugin>      
      <plugin> 
       <groupId>org.apache.tomcat.maven</groupId> 
       <artifactId>tomcat7-maven-plugin</artifactId> 
       <version>2.2</version> 
       <configuration> 
        <port>8080</port> 
        <path>/</path> 
       </configuration> 
      </plugin> 
     </plugins> 
    </build> 

j'ai essayé de l'exécuter:

mvn clean install 
mvn tomcat7:run 

Sortie de console:

C:\Users\workspace_new\HelloWorldApp>mvn tomcat7:run 
    [INFO] Scanning for projects... 
    [INFO] 
    [INFO] ------------------------------------------------------------------------ 
    [INFO] Building HelloWorldApp 0.0.1-SNAPSHOT 
    [INFO] ------------------------------------------------------------------------ 
    [INFO] 
    [INFO] >>> tomcat7-maven-plugin:2.2:run (default-cli) > process-classes @ HelloWorldApp >>> 
    [INFO] 
    [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ HelloWorldApp --- 
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! 
    [INFO] skip non existing resourceDirectory C:\Users\harleen.dhingra\workspace_new\HelloWorldApp\src\main\resources 
    [INFO] 
    [INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ HelloWorldApp --- 
    [INFO] Nothing to compile - all classes are up to date 
    [INFO] 
    [INFO] <<< tomcat7-maven-plugin:2.2:run (default-cli) < process-classes @ HelloWorldApp <<< 
    [INFO] 
    [INFO] --- tomcat7-maven-plugin:2.2:run (default-cli) @ HelloWorldApp --- 
    [INFO] Running war on http://localhost:8080/ 
    [INFO] Using existing Tomcat server configuration at C:\Users\harleen.dhingra\workspace_new\HelloWorldApp\target\tomcat 
    [INFO] create webapp with contextPath: 
    Jun 22, 2016 11:11:37 AM org.apache.coyote.AbstractProtocol init 
    INFO: Initializing ProtocolHandler ["http-bio-8080"] 
    Jun 22, 2016 11:11:37 AM org.apache.catalina.core.StandardService startInternal 
    INFO: Starting service Tomcat 
    Jun 22, 2016 11:11:37 AM org.apache.catalina.core.StandardEngine startInternal 
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.47 
    Jun 22, 2016 11:11:39 AM org.apache.coyote.AbstractProtocol start 
    INFO: Starting ProtocolHandler ["http-bio-8080"] 

Je ne reçois pas d'erreur sur la console, quand je frappe http://localhost:8080/HelloWorldApp/ ou http://localhost:8080/ je devrais obtenir une sortie comme « Bonjour tout le monde: Spring MVC sans configuration XML » au lieu je reçois une erreur 404

+0

Je pense que vous avez manqué l'annotation '@ Controller' sur votre' public AppController' – Patrick

+0

J'ai ajouté le @Controller sur AppController mais j'ai quand même une erreur 404. – Harleen

+0

Avez-vous entendu parler de 'Spring-Boot'? Je suggérerais de l'utiliser car il est construit pour construire des applications Spring complètes sans fichiers de configuration. – Patrick

Répondre

0

manquant @Controller annotation dans la classe Controller.
Votre classe de contrôleur doit être comme

package com.demo.web.controller; 
@Controller 
public class AppController { 
    @ResponseBody 
    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String helloWorld() { 
     return "Hello World: Spring MVC without XML configuration"; 
    } 
} 

Modifier
Voici deux mises à jour de cette réponse
Solution 1
Ajouter ce code à votre classe AppInitializer

applicationContext.setServletContext(servletContext); 

Si la solution ne fonctionnait alors changer votre code comme ceci:
Solution 2 Je l'ai fait de manière légèrement différente et cela a fonctionné.
Voici les changements:

  1. déplacer votre classe AppInitializer à ce paquet (dossier config) & changement à com.demo.config
  2. Utilisez la méthode .register, au lieu de .setConfigLocation comme indiqué ci-dessous
package com.demo.config; 
    public class AppIntializer implements WebApplicationInitializer { 

     @Override 
     public void onStartup(ServletContext servletContext) throws ServletException { 

     System.out.println("Initializing Application for " + servletContext.getServerInfo()); 

     // Create ApplicationContext 
     AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); 

     applicationContext.register(AppConfig.class); 
     applicationContext.setServletContext(servletContext); 

     // Add the servlet mapping manually and make it initialize automatically 
     DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext); 
     ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet); 

     servlet.addMapping("/"); 
     servlet.setAsyncSupported(true); 
     servlet.setLoadOnStartup(1); 
    } 
} 
+0

oups J'ai raté ça, j'ai ajouté le @Controller sur AppController mais j'ai quand même une erreur 404. Y a-t-il autre chose à regarder? – Harleen

+0

avez-vous nettoyé le projet? @Harleen –

+0

J'ai couru deux commandes encore mvn installent propre & mvn tomcat7: exécutez à partir de cmd mais j'obtiens la même erreur 404 une fois que j'ai frappé http: // localhost: 8080/HelloWorldApp/dans le navigateur. – Harleen