栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring Boot:注入自定义上下文路径

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot:注入自定义上下文路径

得到它的工作!

Spring Security docs ( http://docs.spring.io/spring-security/site/docs/3.1.x/reference/security-filter-chain.html ) say: “Spring
Security is only interested in securing paths within the application, so the
contextPath is ignored. Unfortunately, the servlet spec does not define
exactly what the values of servletPath and pathInfo will contain for a
particular request URI. […] The strategy is implemented in the class
AntPathRequestMatcher which uses Spring’s AntPathMatcher to perform a case-
insensitive match of the pattern against the concatenated servletPath and
pathInfo, ignoring the queryString.”

所以我只是重写了

servletPath
and
contextPath
(即使Spring
Security不使用它)。另外,我添加了一些小的重定向,因为通常在命中时将
http://localhost:8080/myContext
您重定向到,
http://localhost:8080/myContext/
并且Spring
Securities Ant Matcher不喜欢缺少的斜杠。

所以这是我的

MultiTenancyFilter
代码:

@Component @Order(Ordered.HIGHEST_PRECEDENCE)public class MultiTenancyFilter extends oncePerRequestFilter {    private final static Pattern pattern = Pattern.compile("^(?<contextPath>/[^/]+)(?<servletPath>.*)$");    @Override    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {        Matcher matcher = pattern.matcher(request.getServletPath());        if(matcher.matches()) { final String contextPath = matcher.group("contextPath"); final String servletPath = matcher.group("servletPath"); if(servletPath.trim().isEmpty()) {     response.sendRedirect(contextPath+"/");     return; } filterChain.doFilter(new HttpServletRequestWrapper(request) {     @Override     public String getContextPath() {         return contextPath;     }     @Override     public String getServletPath() {         return servletPath;     } }, response);        } else { filterChain.doFilter(request, response);        }    }    @Override    protected String getAlreadyFilteredAttributeName() {        return "multiTenancyFilter" + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX;    }}

它仅使用此处提到的URL模式提取contextPath和servletPath:https
://theholyjava.wordpress.com/2014/03/24/httpservletrequest-
requesturirequesturlcontextpathservletpathpathinfoquerystring/

另外,我必须提供一个自定义

getAlreadyFilteredAttributeName
方法,因为否则过滤器将被调用两次。(这导致
contextPath
两次剥离)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/371454.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号