How do I embed Tomcat into a Spring Framework MVC application?… here is a solution to the problem.
How do I embed Tomcat into a Spring Framework MVC application?
I have created the required config/Controller class. But it’s not clear to me how I should orchestrate these classes to run tomcat instances. I know that for spring boot, this is a problem with using SpringApplication.run(..) But I’m trying to explore alternatives that were used before Spring Boot. I’m a bit new to the Spring Framework, please forgive my ignorance. I also don’t use any Java-only XML configuration
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 };
}
}
I’ve created a Controller
@Controller
@RequestMapping("/")
public class HomeController {
@RequestMapping(method = RequestMethod.GET)
public String home(){
return "home";
}
POM file:
<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>
Solution
Finally solved the problem I was having. I added an embedded instance of Tomcat to my POM as recommended by VitalyZ. I configured the embedded tomcat instance in a new class.
Add the following to my POM file
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>8.5.15</version>
</dependency>
A new class named Application.java is created
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();
}
}