【问题标题】:Spring 4 + Embedded Tomcat 7Spring 4 + 嵌入式 Tomcat 7
【发布时间】:2017-01-08 07:00:54
【问题描述】:

我尝试使用 Spring Web MVC 4.3.2 和嵌入式 Tomcat 7.0.64 构建一个 Web 应用程序。

我没有编写正确的 main 方法来启动嵌入式 Tomcat。它适用于 Spring Controller 发送 @ResponseBody 内容 (JSON) 但对于 JSP 视图失败。

public static void main(String[] args) throws Exception {

    String appBase = ".";// What to put here ?

    Tomcat tomcat = new Tomcat();
    String contextPath = "";
    String port = System.getProperty("server.port");
    tomcat.setPort(port == null ? 8080 : Integer.valueOf(port));

    tomcat.getHost().setAppBase(appBase);
    Context context = tomcat.addWebapp(contextPath, appBase);

    // So that it works when in it's launched from IntelliJ or Eclipse
    // Also need that a folder named "META-INF" exists in build/classes/main
    // https://bz.apache.org/bugzilla/show_bug.cgi?id=52853#c19
    ((StandardJarScanner) context.getJarScanner()).setScanAllDirectories(true);

    tomcat.start();
    tomcat.getServer().await();
}

对于 JSP 视图,它说:请求的资源不可用 (WEB-INF/views/home.jsp) HTTP 404

如果我将appBase 变量设置为JSP 所在的绝对路径,它就可以工作。但是,当然,这不是一个解决方案,因为它不能在另一台机器上工作。我需要一个相对路径。

如果我将appBase 变量设置为"src/main/webapp",则Tomcat 无法启动并出现以下错误:java.lang.IllegalArgumentException: Document base C:\blabla\spring-jsp-embedded-tomcat\tomcat.8080\src\main\webapp\src\main\webapp does not exist or is not a readable directory

另外,使用 Gradle fat jar 技术构建的 jar 不包含 WEB-INF 目录。

如何使简单的 Spring MVC 应用程序与嵌入式 Tomcat 和 JSP 一起工作(使用 java -cp path/to/my/jar com.app.Launcher 启动)?

build.gradle:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

jar {
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

repositories {
    maven { url "http://repo1.maven.org/maven2" }
}

dependencies {

    compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.6.2'
    compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.6.2'
    compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.6.2'

    compile 'org.springframework:spring-webmvc:4.3.2.RELEASE'

    compile 'com.fasterxml.jackson.core:jackson-databind:2.7.0'

    compile 'javax.servlet:javax.servlet-api:3.0.1'
    compile 'javax.servlet.jsp:jsp-api:2.2'
    compile 'javax.servlet:jstl:1.2'

    // Embedded Tomcat
    // 2 mandatory libs
    compile 'org.apache.tomcat.embed:tomcat-embed-core:7.0.64'
    compile 'org.apache.tomcat.embed:tomcat-embed-logging-juli:7.0.64'
    // To enable JSPs
    compile 'org.apache.tomcat.embed:tomcat-embed-jasper:7.0.64'

    testCompile group: 'junit', name: 'junit', version: '4.+'

}

Tomcat 启动器:

public class Launcher {

    public static void main(String[] args) throws Exception {
        String contextPath = "";
        // String appBase = "C:/absolute/path/to/webapp/dir"; // It works but of course I need a relative path
        // String appBase = "."; // Works only for Controller sending back ResponseBody (JSON) but fail to find jsp files
        String appBase = "src/main/webapp"; // Tomcat does not start properly

        Tomcat tomcat = new Tomcat();

        String port = System.getProperty("server.port");
        tomcat.setPort(port == null ? 8080 : Integer.valueOf(port));

        tomcat.getHost().setAppBase(appBase);
        Context context = tomcat.addWebapp(contextPath, appBase);

        // So that it works when in it's launched from IntelliJ or Eclipse
        // Also need that a folder named "META-INF" exists in build/classes/main
        // https://bz.apache.org/bugzilla/show_bug.cgi?id=52853#c19
        ((StandardJarScanner) context.getJarScanner()).setScanAllDirectories(true);

        tomcat.start();
        tomcat.getServer().await();
    }

}

Spring Web 应用初始化器:

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

}

网络配置:

@Configuration
@EnableWebMvc
@ComponentScan("com.app")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

文件夹结构:

【问题讨论】:

  • 你为什么选择这些单独使用每个的方法而不是 spring boot?
  • @UserF40 :我知道大多数人都喜欢 Spring Boot。就个人而言,我不喜欢代表我做出决定,我喜欢了解事情是如何发生的。我不喜欢 Spring Boot 的“魔力”。我当然错了。但我不希望在这里对此进行辩论。
  • 在此处添加您可能拥有的任何事实要点stackoverflow.com/q/38633023/6544712
  • 尝试使用与 contextPath 相同的 appBase。如果 contextPath 是 root 则设置 appBase = "ROOT"
  • @Md Zahid Raza。 Tomcat 启动时显示:“java.lang.IllegalArgumentException: Document base C:\blabla\spring-jsp-embedded-tomcat\tomcat.8080\ROOT\ROOT 不存在或不是可读目录”。

标签: spring spring-mvc tomcat embedded-tomcat-7


【解决方案1】:

显然,嵌入式 Tomcat 期望静态资源位于 META-INF/resources 目录中。我遵循了这个:tutorial 并检查了最终 jar 的结构。

所以我修改了 Gradle 构建脚本以将 JSP 放在那里。

sourceSets {
    main {
        resources.srcDirs = ["src/main/webapp"]
        output.resourcesDir = "$buildDir/classes/main/META-INF/resources"
    }
}

现在它可以工作了。但是,我有一种临时工作的感觉。如果有人有更令人满意和更有教育意义的答案,我会很高兴得到它。

【讨论】:

    猜你喜欢
    • 2012-06-11
    • 2012-02-21
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 2017-01-22
    • 2013-08-10
    • 2017-03-12
    • 2018-06-27
    相关资源
    最近更新 更多