Springboot 添加server.servlet.context-path相关使用总结

一、server.servlet.context-path配置的作用

定义: server.servlet.context-path= # Context path of the application. 应用的上下文路径,也可以称为项目路径,是构成url地址的一部分。

server.servlet.context-path不配置时,默认为 / ,如:localhost:8080/xxxxxx

当server.servlet.context-path有配置时,比如 /demo,此时的访问方式为localhost:8080/demo/xxxxxx

二、springboot 2.0变革后的配置区别

1、springboot 2.0之前,配置为 server.context-path

2、springboot 2.0之后,配置为 server.servlet.context-path

三、一个思考

原来的运营项目(已上线),配置文件添加 server.servlet.context-path 配置后,需要在thymleaf 中进行action请求的追加吗?

答案:不需要。

栗子:

前端页面采取form请求

<form th:action="@{/user/userLogin}" method="post" id="userLogin"></form>

action拦截接受方式

@Controller
@RequestMapping("/user")
public class LoginController {

@PostMapping("/userLogin")
public String userLogin(HttpServletRequest request, Model model) {
    

原项目的基础上,追加一个配置

server:
  port: 8080
  servlet:
    context-path: /demo

只需要再开始进入首页时,追加 localhost:8080/demo ,后续的thymleaf中的href和action等无需添加/demo 

 

  • 46
    点赞
  • 154
    收藏
    觉得还不错? 一键收藏
  • 18
    评论
在Spring Boot中,可以通过配置`server.servlet.context-path`来设置应用程序的上下文路径(即context-path)。如果需要统一添加前缀,则可以使用Spring MVC中的`HandlerInterceptor`来拦截请求,并在请求路径前添加前缀。 具体步骤如下: 1. 创建一个`HandlerInterceptor`实现类,实现`preHandle`方法,在该方法中获取请求路径并添加前缀,然后将修改后的路径设置回请求中。 ``` @Component public class PrefixInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String prefix = "/api"; // 前缀 String requestURI = request.getRequestURI(); // 请求路径 String newURI = prefix + requestURI; // 添加前缀 request.getRequestDispatcher(newURI).forward(request, response); // 设置修改后的路径 return true; } } ``` 2. 在Spring Boot配置类中添加`InterceptorRegistry`,并将上面创建的`HandlerInterceptor`添加到其中。 ``` @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Autowired private PrefixInterceptor prefixInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(prefixInterceptor).addPathPatterns("/**"); // 添加拦截器并设置拦截路径 } } ``` 3. 在`Controller`中使用`@RequestMapping`注解指定接口路径,如`/user`,拦截器会自动添加前缀,最终的请求路径为`/api/user`。 ``` @RestController @RequestMapping("/user") public class UserController { @GetMapping("/list") public List<User> list() { // ... } // ... } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值