springboot配置项目的url
在Spring Boot中配置项目的URL主要涉及以下几个方面:
1. 应用上下文路径(Context Path)
方式一:application.properties
# 配置上下文路径
server.servlet.context-path=/myapp# 配置端口
server.port=8080方式二:application.yml
server:servlet:context-path: /myappport: 8080配置后访问地址:http://localhost:8080/myapp
2. 自定义Servlet路径
# 自定义DispatcherServlet的映射路径
spring.mvc.servlet.path=/api/*3. 服务器相关配置
# 服务器地址(绑定特定IP,默认0.0.0.0)
server.address=0.0.0.0# 会话超时时间
server.servlet.session.timeout=30m# 文件上传配置
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB4. 自定义URL路径映射
在Controller中配置:
@RestController
@RequestMapping("/api/v1")
public class UserController {@GetMapping("/users")public List<User> getUsers() {// 访问路径: /myapp/api/v1/usersreturn userService.findAll();}@PostMapping("/users/{id}")public User getUser(@PathVariable Long id) {// 访问路径: /myapp/api/v1/users/1return userService.findById(id);}
}5. 环境特定的配置
application-dev.properties(开发环境)
server.port=8080
server.servlet.context-path=/dev-apiapplication-prod.properties(生产环境)
server.port=80
server.servlet.context-path=/api6. 通过代码配置
@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {// 全局URL前缀configurer.addPathPrefix("api", HandlerTypePredicate.forAnnotation(RestController.class));}
}7. 启用HTTPS
# 启用HTTPS
server.port=8443
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=password
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=tomcat8. 常用配置示例
完整的application.yml示例:
server:port: 8080servlet:context-path: /myapptomcat:uri-encoding: UTF-8max-swallow-size: 2MBspring:mvc:static-path-pattern: /static/**web:resources:static-locations: classpath:/static/注意事项
上下文路径:
server.servlet.context-path会影响所有请求URL端口冲突:确保端口没有被其他应用占用
路径优先级:Controller中的
@RequestMapping会与上下文路径拼接静态资源:上下文路径也会影响静态资源的访问路径
这样配置后,你的应用基础URL就是:http://localhost:8080/myapp
