source

Spring Boot 응용 프로그램에 컨텍스트 경로 추가

bestscript 2022. 11. 24. 23:40

Spring Boot 응용 프로그램에 컨텍스트 경로 추가

Spring Boot 어플리케이션의 컨텍스트루트를 프로그래밍 방식으로 설정하려고 합니다..localhost:port/{app_name}모든 컨트롤러 경로를 추가할 수 있습니다.

다음은 웹 앱용 응용 프로그램 구성 파일입니다.

@Configuration
public class ApplicationConfiguration {

  Logger logger = LoggerFactory.getLogger(ApplicationConfiguration.class);

  @Value("${mainstay.web.port:12378}")
  private String port;

  @Value("${mainstay.web.context:/mainstay}")
  private String context;

  private Set<ErrorPage> pageHandlers;

  @PostConstruct
  private void init(){
      pageHandlers = new HashSet<ErrorPage>();
      pageHandlers.add(new ErrorPage(HttpStatus.NOT_FOUND,"/notfound.html"));
      pageHandlers.add(new ErrorPage(HttpStatus.FORBIDDEN,"/forbidden.html"));
  }

  @Bean
  public EmbeddedServletContainerFactory servletContainer(){
      TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
      logger.info("Setting custom configuration for Mainstay:");
      logger.info("Setting port to {}",port);
      logger.info("Setting context to {}",context);
      factory.setPort(Integer.valueOf(port));
      factory.setContextPath(context);
      factory.setErrorPages(pageHandlers);
      return factory;
  }

  public String getPort() {
      return port;
  }

  public void setPort(String port) {
      this.port = port;
  }
}

메인 페이지의 인덱스 컨트롤러입니다.

@Controller
public class IndexController {

  Logger logger = LoggerFactory.getLogger(IndexController.class);

  @RequestMapping("/")
  public String index(Model model){
      logger.info("Setting index page title to Mainstay - Web");
      model.addAttribute("title","Mainstay - Web");
      return "index";
  }

}

응용 프로그램의 새 루트는 다음 위치에 있어야 합니다.localhost:12378/mainstay 에 있습니다.localhost:12378

무엇이 부족하면 Spring Boot에서 요구 매핑 전에 컨텍스트루트를 추가하지 않습니까?

왜 너만의 해결책을 내놓으려고 하는 거야?스프링 부트는 이미 그것을 지원하고 있습니다.

해 주세요.application.propertiessrc\main\resources 이 속성 파일에서 다음 2개의 속성을 추가합니다.

server.contextPath=/mainstay
server.port=12378

업데이트(스프링 부트 2.0)

2.에서는 ( WebFlux의 ) Spring Boot 2.0 ( Spring MVC spring Spring WebFlux )contextPath는 다음과같이 되었습니다.

server.servlet.context-path=/mainstay

그런 다음 사용자 정의 서블릿 컨테이너에 대한 구성을 제거할 수 있습니다.를 해야 할 의 후처리를 추가할 수 .EmbeddedServletContainerCustomizer구현(에러 페이지 추가 등)을 실시합니다.

으로는 ★★★★★★★★★★★★★★★★★★ 의 속성application.properties로서 기능하는 은, 다른 「기타」 「기타」 「기타」 「기타」 「기타」를 으로써, 수 .application.properties 옆에 JVM JVM 파라미터)를한다.-Dserver.port=6666를 참조해 주세요.

참조 가이드, 특히 속성 섹션을 참조하십시오.

이 클래스는EmbeddedServletContainerCustomizer의:contextPath""에서는 .드음음, 음음음음 the the the the the 를 설정하고 있습니다contextPathTomcatEmbeddedServletContainerFactory 하다.ServerProperties는 이 ."". ( 행은null로는 " " " " 입니다.""를 '''로 설정합니다''""그 결과, 자신의 것을 무효로 합니다).

Spring Boot을 사용하는 경우 Bean initializing을 통해 서버 속성을 설정할 필요가 없습니다.

기본할 수 개 있는 「할 수 .「」파일은 「프로퍼티」입니다.application 한다.src\main\resources응용 프로그램 구조에서 사용할 수 있습니다. 가지 형식의 "properties"로할 수 있습니다.

  1. .yml

  2. .properties

설정을 지정하거나 설정하는 방법은 형식에 따라 다릅니다.

의 경우, 번호 「」를 했을 경우, 「」로 합니다..properties '요.'라고 하는 이 있을 거예요application.properties아래src\main\resources과 같은

server.port = 8080
server.contextPath = /context-path

.yml 확즉즉즉즉즉,application.yml에는, 「 」, 「 」, 「 」, 「 」, 「 」, 「 YAML

server:
    port: 8080
    contextPath: /context-path

스프링 부트의 일반적인 속성에 대해서는, 다음의 링크를 참조해 주세요.

https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Spring Boot 2.0.0을 사용하는 경우 다음을 사용합니다.

server.servlet.context-path

server.servate-path 또는 server.servlet.servate-path [springboot 2.0.x부터]속성은 임베디드 컨테이너(예: 임베디드 Tomcat)에 전개하는 경우에만 기능합니다.예를 들어 외부 Tomcat에 대한 전쟁으로 애플리케이션을 배포하는 경우 이러한 속성은 영향을 미치지 않습니다.

다음 답변 참조:https://stackoverflow.com/a/43856300/4449859

올바른 속성은 다음과 같습니다.

server.servlet.path

DispatcherServlet 경로를 설정합니다.

그리고.

server.servlet.context-path

그 아래에 있는 어플리케이션콘텍스트의 패스를 설정합니다.

포트와 컨텍스트 경로를 쉽게 추가하여 [src\main\resources].properties 파일과 .yml 파일에 설정을 추가할 수 있습니다.

어플.porperties 파일컨피규레이션

server.port = 8084
server.contextPath = /context-path

application.yml 파일컨피규레이션

server:
port: 8084
contextPath: /context-path

스프링 부츠에서 프로그램 방식으로 변경할 수도 있습니다.

@Component
public class ServerPortCustomizer implements     WebServerFactoryCustomizer<EmbeddedServletContainerCustomizer > {

@Override
public void customize(EmbeddedServletContainerCustomizer factory) {
    factory.setContextPath("/context-path");
    factory.setPort(8084);
}

}

다른 방법을 추가할 수도 있습니다.

@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {SpringApplication application =     new pringApplication(MyApplication.class);
    Map<String, Object> map = new HashMap<>();
    map.put("server.servlet.context-path", "/context-path");
    map.put("server.port", "808");
    application.setDefaultProperties(map);
    application.run(args);
    }       
}

java 명령어 spring boot 1을 사용합니다.x

java -jar my-app.jar --server.contextPath=/spring-boot-app     --server.port=8585 

java 명령어 spring boot 2를 사용합니다.x

java -jar my-app.jar --server.servlet.context-path=/spring-boot-app --server.port=8585 

속성 파일의 간단한 엔트리를 사용하여 컨텍스트 루트 경로를 변경할 수 있습니다.

application.properties

### Spring boot 1.x #########
server.contextPath=/ClientApp

### Spring boot 2.x #########
server.servlet.context-path=/ClientApp

We can set it in the 에 설정할 수 있습니다.application.properties as ~하듯이API_CONTEXT_ROOT=/therootpath

그리고 우리는 아래와 같이 자바 클래스에서 접속합니다.

@Value("${API_CONTEXT_ROOT}")
private String contextRoot;

server.contextPath=/mainstay

JBOSS에 전쟁파일이 하나 있으면 도움이 돼요각각 jboss-web.xml이 포함된 여러 전쟁 파일에서는 작동하지 않았습니다.jboss-web.xml을 콘텐츠가 있는 WEB-INF 디렉토리에 넣어야 했습니다.

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web xmlns="http://www.jboss.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-web_5_1.xsd">
    <context-root>mainstay</context-root>
</jboss-web>

스프링 부트 1.5의 경우:

Add the following property in 다음 속성을 에 추가합니다.application.properties::::

server.context-path=/demo

참고: 의:/demo is your context path URL.는 컨텍스트 경로 URL 입니다.

We can set it using 를 사용하여 설정할 수 있습니다.WebServerFactoryCustomizer. 스프링 부팅 메인 방법 클래스에 직접 추가할 수 있습니다.Spring Application Context (스프링 애플리케이션 컨텍스트)스프링 부트메인

@Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
      webServerFactoryCustomizer() {
        return factory -> factory.setContextPath("/demo");
}

Spring Boot 2.x를 사용하여 명령줄에서 컨텍스트패스 속성을 전달할 경우 다음과 같이 double // 를 입력합니다.

--server.servlet.context-path=//your-path

창문으로 뛰어다니는데 효과가 있었어요.

Spring Boot: 2.1.6에서 다음과 같이 사용할 수 있습니다.

server.servlet.context-path=/api-path

Spring Boot 2 이하 버전에서는 아래 코드를 사용해야 합니다.

server:
   context-path: abc    

또한 스프링 부트 2+ 버전의 경우 아래 코드를 사용하십시오.

server:
  servlet:
    context-path: abc

application.yml 및 2.0 이상의 스프링 버전을 사용하는 경우 다음과 같이 설정합니다.

server:
  port: 8081
  servlet:
     context-path: /demo-api

모든 API 콜은 http://localhost:8081/demo-api/와 같습니다.

이 속성을 스프링 속성 파일에 추가할 수 있습니다.

spring.data.rest.basePath=/your_path
<!-- Server port-->

server.port=8080

<!--Context Path of the Application-->

server.servlet.context-path=/ems

server.servlet.servlet-path = / demo note에는 따옴표가 없고 '/' 앞에 있는 값만 포함되어 있지 않은 경우 이 값은 application.properties 파일에 들어갑니다.

spring-boot-starter-webflux 를 사용하는 경우:

spring:
  webflux:
    base-path: /api

신께 맹세코...매번 이걸 까먹어요.

컨텍스트 경로는 코드에 직접 통합할 수 있지만 재사용할 수 없으므로 권장되지 않으므로 코드를 넣은 폴더의 application.properties 파일 server.contextPath=/name에 코드를 넣은 폴더의 contextPath= 이름/참고:슬래시를 주의하여 확인하십시오.

언급URL : https://stackoverflow.com/questions/20405474/add-context-path-to-spring-boot-application