Java springboot war使用嵌入式tomcat,但不使用外部tomcat

Java springboot war使用嵌入式tomcat,但不使用外部tomcat,java,spring-boot,maven,tomcat9,Java,Spring Boot,Maven,Tomcat9,我一直在使用SpringSecurity开发springboot 2.3.4应用程序。它与嵌入式tomcat一起工作。我们想让它与外部应用服务器如tomcat和jboss一起工作。我已尝试在外部tomcat服务器中部署war文件。当到达端点时,我收到404错误代码。这是我的pom文件: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apac

我一直在使用SpringSecurity开发springboot 2.3.4应用程序。它与嵌入式tomcat一起工作。我们想让它与外部应用服务器如tomcat和jboss一起工作。我已尝试在外部tomcat服务器中部署war文件。当到达端点时,我收到404错误代码。这是我的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.teradata</groupId>
    <artifactId>modelstudio</artifactId>
    <version>1</version>
    <name>modelstudio</name>
    <packaging>war</packaging>
    <description>ModelStudio Application</description>

    <properties>
       <java.version>13</java.version>
       <start-class>
            com.teradata.modelstudio.ModelStudioApplication
       </start-class>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.skyscreamer</groupId>
                    <artifactId>jsonassert</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.teradata.jdbc</groupId>
            <artifactId>terajdbc4</artifactId>
            <version>17</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20200518</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.json</groupId>
                    <artifactId>json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
    <finalName>modelstudio</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>static/**</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>ModelStudioUI/**</exclude>
                    <exclude>static/**</exclude>
                </excludes>
            </resource>
        </resources>
    </build>

</project>

我的安全配置文件:

package com.teradata.modelstudio.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.teradata.modelstudio.filter.JwtFilter;
import com.teradata.modelstudio.payload.JwtAuthenticationResponse;
import com.teradata.modelstudio.security.JwtAuthenticationEntryPoint;
import com.teradata.modelstudio.service.CustomAuthenticationProviderService;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProviderService authenticationProviderService;

    @Autowired
    private JwtFilter jwtFilter;
    
    @Autowired
    JwtAuthenticationEntryPoint unauthorizedHandler;
    
    @Autowired
    private com.teradata.modelstudio.filter.SimpleCORSFilter simpleCORSFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
        .antMatchers(
                HttpMethod.GET,
              "/",
              "/*.html",
              "/*.svg",
              "/*.png",
              "/*.woff",
              "/*.woff2",
              "/*.svg",
              "/*.jpg",
              "/*.json",
              "/favicon.ico",
              "/**/*.html",
              "/**/*.css",
              "/**/*.js",
              "/**/*.svg",
              "/**/*.png",
              "/**/*.jpg",
              "/**/*.ico",
              "/**/*.icons",
              "/resources/**",
              "/assets/",
              "/static/**",
              "/h2-console/**"
        ).permitAll()
        .antMatchers("/auth/**", "/dbcontent/**")
                .permitAll()
                .anyRequest().authenticated()
                .and().exceptionHandling().and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(simpleCORSFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProviderService);
    }
    
    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
我的一个控制器类是:

package com.teradata.modelstudio.controllers;

import java.io.File;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.teradata.modelstudio.exception.ModelStudioException;
import com.teradata.modelstudio.utils.Logger;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;

@RestController
@RequestMapping("dbcontent")
public class DBContentController {
    
    @GetMapping(path="servers", produces = "application/json")
    public ResponseEntity<?> getServers() {
        try {
            String dbConFilePath = System.getProperty("user.dir")+File.separator+"db-con";
            File file = new File(dbConFilePath);
            String content = FileUtils.readFileToString(file, "utf-8");
            // Convert JSON string to JSONObject
            JSONObject fileContents = new JSONObject(content);
            return ResponseEntity.ok(fileContents.toString());
        } catch(Exception e) {
            Logger.error("Unable to get servers: "+e.getMessage());
            throw new ModelStudioException(e.getMessage());
        }
    }
    
}

使用嵌入式tomcat serever,我点击:

localhost:8080/dbcontent/servers

我在使用外部设备时会得到以下结果:

localhost:8080/modelstudio/dbcontent/servers

我得到404


任何人都可以帮助我,并建议我如何使用外部服务器(如tomcat)解决此问题。

您的
spring boot starter web
依赖项已提供。这意味着在tomcat上部署时它不可用,基本上您将丢失整个web部件。您可能想做的是添加
springbootstartertomcat
依赖项,并标记提供的依赖项(以便不包括tomcat依赖项)。因此,添加它并从
springbootstarterweb
中删除范围。我已经有了这个依赖项,并将其标记为提供的。我对它进行了一些搜索,发现了两个可能导致问题的原因。1-当我们在springboot中运行嵌入式tomcat时,默认情况下它知道从何处到服务器静态内容。在这种情况下,静态内容位于src/main/resource/static文件夹中。所以,如果我们使用localhost:8080,那么这意味着requestURI是“/”,它需要提供index.html。对于外部tomcat,它不知道从哪里提供这个静态内容。所以在外部的情况下,路径是localhost:8080/modelstudio,requestURI变成/modelstudio/,它找不到任何处理程序并返回404。除去这个范围,没有SpringWeb,应用程序就不会启动,因为没有web类。它与嵌入的tomcat一起工作,因为它添加了那些由于特殊类加载器而提供的依赖项。2-另一个问题是,当我们使用嵌入的tomcat时,路径不包括服务器上下文路径。在外部tomcat的情况下,所有请求都使用上下文路径着陆。因此,在Embedded中,uri是“/auth/login”,但在external中,它将变成“/modelstudio/auth/login”。所以安全过滤器不让它去,并会要求授权,因此403禁止的错误。那么我们如何适应这些上下文路径呢。是否需要在所有端点路径中包含?
package com.teradata.modelstudio.controllers;

import java.io.File;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.teradata.modelstudio.exception.ModelStudioException;
import com.teradata.modelstudio.utils.Logger;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;

@RestController
@RequestMapping("dbcontent")
public class DBContentController {
    
    @GetMapping(path="servers", produces = "application/json")
    public ResponseEntity<?> getServers() {
        try {
            String dbConFilePath = System.getProperty("user.dir")+File.separator+"db-con";
            File file = new File(dbConFilePath);
            String content = FileUtils.readFileToString(file, "utf-8");
            // Convert JSON string to JSONObject
            JSONObject fileContents = new JSONObject(content);
            return ResponseEntity.ok(fileContents.toString());
        } catch(Exception e) {
            Logger.error("Unable to get servers: "+e.getMessage());
            throw new ModelStudioException(e.getMessage());
        }
    }
    
}

package com.teradata.modelstudio;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication(
          exclude = { DataSourceAutoConfiguration.class, 
             HibernateJpaAutoConfiguration.class,
             DataSourceTransactionManagerAutoConfiguration.class, 
             })
public class ModelstudioApplication extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(ModelstudioApplication.class, args);
    }
    
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(ModelstudioApplication.class);
    }

}