【发布时间】:2018-10-28 19:28:38
【问题描述】:
我是 Servlet 的新手。我需要生成自定义值 cookie。在下面提到的代码中,会生成会话 cookie,但我还需要一个自定义值。
public ServletContextInitializer servletContextInitializer() {
servletContext -> servletContext.getSessionCookieConfig().setName("sessiondemo");
}
我的 Servlet 代码如下。在注释行中,我需要添加 cookie。基本上,我将重定向到这里的请求来初始化 servlet 会话,同时我还需要在 servletcontext 中生成一个名为 hello 和 value world 的 cookie。
public class WebSecurityConfigurer extends WebMvcConfigurerAdapter {
@Autowired
private Environment environment;
UserDetails user;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
@Bean
public ServletContextInitializer servletContextInitializer() {
/* This code doesn't work here. I need to use here to set up the cookie
Cookie cookie = new Cookie("YourCookieName", "CookieStringValue");
cookie.setMaxAge(10 * 365 * 24 * 60 * 60); // set cookie for 10 years
response.addCookie(cookie); */
return servletContext -> servletContext.getSessionCookieConfig()
.setName("oneKosmosIdpSessionId");
}
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private IdpConfiguration idpConfiguration;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/metadata", "/favicon.ico", "/api/**", "/*.css",
"/css/**", "/js/**", "/img/**", "/fonts/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/user.html", true)
.failureUrl("/login?error=true")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/");
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new AuthenticationProvider(idpConfiguration));
}
}
}
【问题讨论】:
-
您已将会话跟踪 cookie(通常为
JSESSIONID)重命名为sessiondemo。自定义值对您来说是什么意思? -
意味着我必须再创建一个 cookie,比如 flag="true"。我不想删除这个 sessiondemo cookie 需要再添加一个。
标签: java spring-boot servlets spring-security thymeleaf