springboot移除url中的sessionid

by kevin 21. 二月 2024 14:26 >

1. 配置文件中添加

[sourcecode language='xml'  padlinenumbers='true']
server.servlet.session.tracking-modes=COOKIE
[/sourcecode]

2. 对每个请求的url判断,重新改写。

package com.ac;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SessionUrlInterceptor extends HandlerInterceptorAdapter {

    @Value("${sessionUrlEnable}")
    private boolean sessionUrlEnable;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, ServletException {
        if (sessionUrlEnable && StringUtils.isNotBlank(request.getSession().getId())) {
            String requestURI = request.getRequestURI();
            String uriSession = ";jsessionid=" + request.getSession().getId();
            LogUtils.logInfo("requestURI:" + requestURI + " sessionURI:" + uriSession);
            if (requestURI.indexOf(uriSession) != -1) {
//                LogUtils.logInfo("requestURI:" + requestURI + " Forward");               
                requestURI = requestURI.replace(uriSession, "");               
                request.getRequestDispatcher(requestURI).forward(request, response);
                return false;
            }
        }
        return true;
    }
}

分享到: 更多