是否可以设置cookiePath
应用程序名称的值(自动)?例如,我有一个 test.war,所以它可以在 bla.com/test/ 上使用,所以我希望我的 cookie 的路径是/test/
而不是/
默认值。谢谢
问问题
2840 次
2 回答
3
创建时,CookieLocaleResolver
您可以设置path
,但它将被硬编码。
前任
<bean id="localeResolver" class="CookieLocaleResolver">
<property name="cookiePath" value="test" />
</bean>
另一种可能的解决方案是覆盖 LocaleResolver
public class MyCookieLocaleResolver extends CookieLocaleResolver {
@Override
public void setLocale(HttpServletRequest request,
HttpServletResponse response, Locale locale) {
if (locale != null) {
// Set request attribute and add cookie.
request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME, locale);
addCookie(response, locale.toString());
} else {
// Set request attribute to fallback locale and remove cookie.
request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
determineDefaultLocale(request));
removeCookie(response);
}
}
public void addCookie(HttpServletRequest request,
HttpServletResponse response, String cookieValue) {
Cookie cookie = createCookie(request, cookieValue);
Integer maxAge = getCookieMaxAge();
if (maxAge != null) {
cookie.setMaxAge(maxAge);
}
if (isCookieSecure()) {
cookie.setSecure(true);
}
response.addCookie(cookie);
if (logger.isDebugEnabled()) {
logger.debug("Added cookie with name [" + getCookieName()
+ "] and value [" + cookieValue + "]");
}
}
protected Cookie createCookie(HttpServletRequest request, String cookieValue) {
Cookie cookie = new Cookie(getCookieName(), cookieValue);
if (getCookieDomain() != null) {
cookie.setDomain(getCookieDomain());
}
cookie.setPath(request.getContextPath());
return cookie;
}
}
于 2013-06-18T09:40:44.773 回答
1
如果使用 ServletContainer >= 2.5 和 spring 注解,则可以使用以下代码获取 ContextPath,因此您不必硬编码:
@EnableWebMvc
@Configuration
@ComponentScan("com.controller")
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private ServletContext servletContext;
@Bean
public LocaleResolver localeResolver(){
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setDefaultLocale(new Locale("en"));
resolver.setCookieName("locale");
resolver.setCookiePath(servletContext.getContextPath());
resolver.setCookieMaxAge(31536000);
return resolver;
}
}
于 2017-05-04T02:34:54.530 回答