我已经创建了所需的配置/控制器类。但是我不清楚我应该如何协调这些类以使用运行tomcat实例。我知道使用Spring Boot是使用SpringApplication.run(..)的问题。但是我正在尝试探索Spring Boot之前使用的替代方法。我对Spring Framework有点陌生,所以请原谅我的无知。我也没有仅使用Java使用任何XML配置
public class SpittrWebAppInitializer 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 }; } }
我已经创建了一个控制器
@Controller @RequestMapping("/") public class HomeController { @RequestMapping(method = RequestMethod.GET) public String home(){ return "home"; }
POM文件:
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.9.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.9.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies>
终于解决了我遇到的问题。就像VitalyZ建议的那样,我将 Tomcat 的嵌入式实例添加到了我的POM中。我在新类中配置了嵌入式tomcat实例。
将以下内容添加到我的Pom文件中
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>8.5.15</version> </dependency>
创建一个名为Application.java的新类
public class Application { public static void main(String[] args) throws Exception { String webAppDirLocation = "src/main/"; Tomcat tomcat = new Tomcat(); //Set Port # tomcat.setPort(8080); StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webAppDirLocation).getAbsolutePath()); tomcat.start(); tomcat.getServer().await(); } }