【知识点】springboot项目配置项目访问根路径

在Spring Boot中,可以通过配置属性来设置应用的Context Path(上下文路径)。Context Path是URL中应用的根路径,用于区分不同的应用。以下是几种常见的设置Context Path的方式:

1,使用application.properties/application.yml文件配置:

在src/main/resources目录下的application.properties或application.yml文件中,添加以下属性配置:

# 设置Context Path为/myapp
server.servlet.context-path=/myapp

或者在application.yml文件中添加以下配置:

# 设置Context Path为/myapp
server:
  servlet:
    context-path: /myapp

这样配置之后,应用的URL将以/myapp开头。

2,使用命令行参数配置:

在运行Spring Boot应用时,可以通过命令行参数来配置Context Path。例如:

java -jar myapp.jar --server.servlet.context-path=/myapp

这样配置之后,应用的URL将以/myapp开头。

3,使用编程方式配置:

在Spring Boot应用的启动类中,可以通过编程方式来配置Context Path。例如:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.web.context.WebApplicationContext;

@SpringBootApplication
public class MyAppApplication implements ServletContextInitializer {

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

    @Override
    public void onStartup(javax.servlet.ServletContext servletContext) throws javax.servlet.ServletException {
        String contextPath = "/myapp";
        WebApplicationContext webApplicationContext = createRootApplicationContext(servletContext);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
        servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext)).addMapping(contextPath + "/*");
    }

    private WebApplicationContext createRootApplicationContext(javax.servlet.ServletContext servletContext) {
        AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext();
        context.setServletContext(servletContext);
        // 配置其他的Bean和组件
        return context;
    }

}

这样配置之后,应用的URL将以/myapp开头。

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值