Spring Boot:从网址中删除jsessionid


问题内容

如何从网址中删除jsessionid?

我正在使用Spring Boot MVC(没有Spring Security;嵌入了tomcat)。

我已经读过,可以通过将disableUrlRewriting设置为“ true”来完成。但这看起来像一个Spring
Security解决方案,我不使用它(这是一个没有登录的简单项目;只有页面;存在会话控制器,并且必须是会话控制器)。

我之所以这样问是因为GoogleBot正在创建包含ID的网址。

编辑:我用以下描述的解决方案解决了它:https : //randomcoder.org/articles/jsessionid-considered-
harmful


问题答案:

我创建了一个快速且肮脏的spring-boot应用程序,这就是我想到的。

生成的ServletInitializer可以按以下方式更改:

package com.division6.bootr;

import java.util.Collections;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // This can be done here or as the last step in the method
        // Doing it in this order will initialize the Spring
        // Framework first, doing it as last step will initialize
        // the Spring Framework after the Servlet configuration is 
        // established
        super.onStartup(servletContext);

        // This will set to use COOKIE only
        servletContext
            .setSessionTrackingModes(
                Collections.singleton(SessionTrackingMode.COOKIE)
        );
        // This will prevent any JS on the page from accessing the
        // cookie - it will only be used/accessed by the HTTP transport
        // mechanism in use
        SessionCookieConfig sessionCookieConfig=
                servletContext.getSessionCookieConfig();
        sessionCookieConfig.setHttpOnly(true);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringBootrApplication.class);
    }

}

作者注

我不确定该何时引入,但是通过引入以下参数,无需编写代码即可实现相同的目的:

  • server.servlet.session.cookie.http-only = true
  • server.servlet.session.tracking-modes = cookie