All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.luues.core.cookie.CookieConfig Maven / Gradle / Ivy

There is a newer version: 2.0.1.RELEASE
Show newest version
package com.luues.core.cookie;

import com.luues.core.config.BeanConfig;
import org.apache.catalina.Context;
import org.apache.tomcat.util.http.LegacyCookieProcessor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.util.SocketUtils;

/**
 * 解决jar启动 cookie无法存储问题
 */
@Configuration("core.cookieConfig")
public class CookieConfig {

    @Value("${server.port:0}")
    private int serverPort;

    @Bean(value = "core.cookieProcessorCustomizer")
    @DependsOn({"springContextHolder","coreProperties"})
    public WebServerFactoryCustomizer cookieProcessorCustomizer() {
        return new WebServerFactoryCustomizer() {
            @Override
            public void customize(WebServerFactory factory) {
                if (factory instanceof TomcatServletWebServerFactory) {
                    ((TomcatServletWebServerFactory) factory).addContextCustomizers(
                            new TomcatContextCustomizer() {
                                @Override
                                public void customize(Context context) {
                                    //这样设置后,当浏览器有无法识别的cookie时,会直接返回404(测试中发现,不知原因,如_——开头的cookie key)
                                    if(BeanConfig.getBeanConfig().isLegacyCookieProcessor())
                                        context.setCookieProcessor(new LegacyCookieProcessor());
                                }
                            }
                    );
                }
                if (factory instanceof ConfigurableWebServerFactory) {
                    //解决springcloud下使用随机端口,eureka界面显示的应用端口跟应用实际端口不一致问题
                    if(serverPort == 0){
                        serverPort = SocketUtils.findAvailableTcpPort(1, 65534);
                    }
                    ((ConfigurableWebServerFactory) factory).setPort(serverPort);
                    System.getProperties().put("server.port", serverPort);
                }
            }
        };
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy