springboot controller 增加指定前缀的两种实现方法
时间:2023-03-15 09:24:03|栏目:JAVA代码|点击: 次
controller 增加指定前缀
1、增加配置
server.servlet.context-path: /api
这种是最常见的,加上这个配置后,所有的url,必须带上/api的前缀,才能访问到该url
2、过滤拦截
这种是加上/api也可以访问,不加/api也可以访问,适合项目重构修改的适合用
import org.apache.commons.lang.StringUtils; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @Configuration @Order(1) @WebFilter(filterName = "urlFilter", urlPatterns = "/api/*") public class UrlFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String servletPath = httpRequest.getServletPath(); if (StringUtils.isNotBlank(servletPath) && servletPath.startsWith("/api")) { String newPath = servletPath.substring(4); request.getRequestDispatcher(newPath).forward(request, response); } else { chain.doFilter(request, response); } } @Override public void destroy() { } }
springboot服务端口、项目前缀的配置
在application.properties中配置
server.port: 8081 server.context-path: /demo
上一篇:Spring Cloud负载均衡组件Ribbon原理解析
栏 目:JAVA代码
本文标题:springboot controller 增加指定前缀的两种实现方法
本文地址:http://www.codeinn.net/misctech/227446.html