我是自己实现了一个 HttpSessionIdResolver 来让 CookieHttpSessionIdResolver 和 HeaderHttpSessionIdResolver 自动选择:
```
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;
import org.springframework.web.accept.ContentNegotiationStrategy;
public class SmartHttpSessionIdResolver implements HttpSessionIdResolver {
protected final HttpSessionIdResolver browser;
protected final HttpSessionIdResolver api;
private final RequestMatcher browserMatcher;
public SmartHttpSessionIdResolver(
ContentNegotiationStrategy contentNegotiationStrategy) {
this.browser = new CookieHttpSessionIdResolver();
this.api = HeaderHttpSessionIdResolver.xAuthToken();
MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(
contentNegotiationStrategy, Arrays.asList(MediaType.TEXT_HTML));
matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
RequestHeaderRequestMatcher javascript = new RequestHeaderRequestMatcher(
"X-Requested-With", "XMLHttpRequest");
this.browserMatcher = new OrRequestMatcher(
Arrays.asList(matcher, javascript));
}
/**
* {@inheritDoc}
*/
@
Override public List<String> resolveSessionIds(HttpServletRequest request) {
return getResolver(request).resolveSessionIds(request);
}
/**
* {@inheritDoc}
*/
@
Override public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
getResolver(request).setSessionId(request, response, sessionId);
}
/**
* {@inheritDoc}
*/
@
Override public void expireSession(HttpServletRequest request, HttpServletResponse response) {
getResolver(request).expireSession(request, response);
}
protected HttpSessionIdResolver getResolver(HttpServletRequest request) {
return this.browserMatcher.matches(request) ? this.browser : this.api;
}
}
```