解决url带jsessionid问题(springboot版)

it2024-11-15  2

1.问题背景:

我的项目不使用cookie,使用sessionStorage,走前后端分离路线,但是有一个机能用的thymeleaf继承以前的项目。

vue访问springboot时shiro+jwt+redis,没有问题。

thymeleaf访问springboot时shiro拦截了在jsessionid的url,导致css样式请求报400,返回画面没有样式。

2.解决方案

从上检索到的去掉jsessionid都是springmvc版的,追加过滤器解决,过滤器注册在web.xml。

我就记录下自己springboot版,完整的代码。

①pom.xml引入

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

②过滤器 RemoveUrlJsessionIdFilter.java 

注解 @WebFilter(urlPatterns = "/*",filterName = "removeUrlJsessionIdFilter")相当于web.xml中的filter-mapping。

import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; @WebFilter(urlPatterns = "/*",filterName = "removeUrlJsessionIdFilter") public class RemoveUrlJsessionIdFilter implements Filter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; // skip non-http requests if (!(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return; } //从url中删除jsessionid // isRequestedSessionIdFromURL():Checks whether the requested session ID came in as part of the request URL. if (httpServletRequest.isRequestedSessionIdFromURL()) { HttpSession session = httpServletRequest.getSession(); if (null != session) { session.invalidate(); } } // wrap response to remove URL encoding HttpServletResponseWrapper wrappedResponse = new HttpServletResponseWrapper(httpServletResponse) { @Override public String encodeRedirectUrl(String url) { return url; } @Override public String encodeRedirectURL(String url) { return url; } @Override public String encodeUrl(String url) { return url; } @Override public String encodeURL(String url) { return url; } }; // process next request in chain chain.doFilter(request, wrappedResponse); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }

 

③springboot启动器 SysCbhsApplication.java

追加注解【@ServletComponentScan】,相当于在springMvc的web.xml中的filter。

@Slf4j @SpringBootApplication @ServletComponentScan public class SysCbhsApplication { public static void main(String[] args) { SpringApplication.run(SysCbhsApplication.class, args); log.info("【 系统服务已启动 】"); } }

 

最新回复(0)