简体   繁体   中英

Spring JavaConfig and Tomcat 8

I have a Spring 4 web application (webapp-module.war) working and running locally in eclipse using Java 8, tomcat 8 and JavaConfig (no web.xml):

在此处输入图片说明

But when I deploy to tomcat 8 (same version I am using locally in eclipse) on a remote Ubuntu server I get:

在此处输入图片说明

I verified host and port which are correct. There is no error in the log (/var/lib/tomcat8/logs/catalina.out)

Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig undeploy
INFO: Undeploying context [/webapp-module]
Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /var/lib/tomcat8/webapps/webapp-module.war
Jun 21, 2016 10:32:46 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 21, 2016 10:32:46 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deployment of web application archive /var/lib/tomcat8/webapps/webapp-module.war has finished in 1,870 ms
root@vmi63860:/var/lib/tomcat8/logs# 

The access log contains:

root@vmi63860:/var/log/tomcat8# cat localhost_access_log.2016-06-22.txt 
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /webapp-module/ HTTP/1.1" 404 1040
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /favicon.ico HTTP/1.1" 404 1034
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:50 +0200] "GET /webapp-module/hello HTTP/1.1" 404 1050

Where xx.xxx.xxx.xx is the IP of my local machine from where I try to access the web app in my browser.

I took a look at: Spring Java Config: Tomcat deploy without web.xml but it does not really provide a solution.

Details on my project below:

Sources

在此处输入图片说明

Config.java

@Configuration // Marks this class as configuration
// Specifies which package to scan
@ComponentScan("com.samples")
// Enables Spring's annotations
@EnableWebMvc
public class Config {

  @Bean
  public UrlBasedViewResolver setupViewResolver() {
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);
    return resolver;
  }

}

WebInitializer.java

public class WebInitializer implements WebApplicationInitializer {

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

    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(Config.class);
    ctx.setServletContext(servletContext);

    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);

  }

}

HelloController.java

@Controller
public class HelloController {

  @RequestMapping("/")
  public String home() {
    return "index";
  }

  @RequestMapping("/hello")
  public String showhello(ModelMap model) {
    model.addAttribute("message", "Hello Spring MVC Framework!");
    return "hello";
  }

}

Sorry previously I was too hasty

It seems that spring context is not at all loaded.

I guess the problem is in this piece of code:

public class WebInitializer implements WebApplicationInitializer {

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

    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(Config.class);
    ctx.setServletContext(servletContext);

    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);

  }

}

You used ctx.register(Config.class);

In any case I always used this kind of initialization:

public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.scan("com.spring");
        rootContext.setConfigLocations(new String[]{"com.spring.config.WebAppContextConfig", "com.spring.config.AppConfig"});
        // Manages the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(rootContext));

        // Declare dispatcher servlet. Handles requests into the application
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
                new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

    }

}

As you can see I used rootContext.setConfigLocations in order to specify where to find the spring configuration classes

In any case Here you can find a working sample I successfully deployed it on tomcat 8.0.39 and 8.5.4

Hope it's useful

Angelo

Turns out that I was not doing anything wrong in code. Tomcat server is configured to use strict servlet compliance.

org.apache.catalina.STRICT_SERVLET_COMPLIANCE=true 

This setting affects multiple other properties ( see here ). One of them is "The resourceOnlyServlets attribute of any Context element". Setting this value to "jsp" in application's context.xml solved the problem.

Comma separated list of Servlet names (as used in /WEB-INF/web.xml) that expect a resource to be present. Ensures that welcome files associated with Servlets that expect a resource to be present (such as the JSP Servlet) are not used when there is no resource present. This prevents issues caused by the clarification of welcome file mapping in section 10.10 of the Servlet 3.0 specification. If the org.apache.catalina.STRICT_SERVLET_COMPLIANCE system property is set to true, the default value of this attribute will be the empty string, else the default value will be jsp.

Add finalName as ROOT in your pom.xml . This will create ROOT.war file in your target folder.

    <build>
        <plugins>
<!--All plugins are here -->
        </plugins>
        <finalName>ROOT</finalName>
    </build>

After that if you deploy ROOT.war file in your tomcat. Then your accessing url will be http://localhost:8080

Hope it will solve your issue.

For further checking, please go through http://localhost:8080/manager/html it will call for username and password. Check that is set or not.

If not set, please go through this tutorial: Can't access Tomcat 8 Manager App as suggested by E-Riz

For full example, go through this tutorial: http://websystique.com/springmvc/spring-4-mvc-helloworld-tutorial-annotation-javaconfig-full-example/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM