user6022251
user6022251

Reputation:

Intellij spring boot app does not work from tomcat

This is my class

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Configuration
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class TomcatIcınApplication {

    public static void main(String[] args) {
        SpringApplication.run(TomcatIcınApplication.class, args);
    }
}

@RestController
class GreetingController {

    @RequestMapping("/hello/hi")
    String hello( ) {
        return "Hello, xx!";
    }
}

When i run application and open localhost:8080/hello/hi, i can see the output. But from Edit Configurations, when i add tomcat server on port 8081 as localhost:8081/hello and run tomcat this time, it invokes app and opens page but it is empty.

Why can't i see my output?

Upvotes: 3

Views: 9829

Answers (1)

Ali Dehghani
Ali Dehghani

Reputation: 48123

When you simply run the application, Spring Boot will use its embedded tomcat server to run your application. If you're planning to use another standalone tomcat server to deploy your boot application, which i do not recommend, first you should tell your build tool to package your application as a war not jar. Then modify your main boot application entry point to support that and finally deploy your war file to your tomcat server either by using Intellij or manually.

The first step in producing a deployable war file is to provide a SpringBootServletInitializer subclass and override its configure method. In you case:

@SpringBootApplication
public class TomcatIcınApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(TomcatIcınApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(TomcatIcınApplication.class, args);
    }
}

Then tell your build tool to package your application as a war, not jar. If you're using maven, simply add:

<packaging>war</packaging>

And finally mark the spring-boot-starter-tomcat as provided:

<dependencies>
    <!-- ... -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- ... -->
</dependencies>

You read more about spring boot Traditional deployment here.

Upvotes: 12

Related Questions