在Spring MVC中共享cookie

时间:2015-11-26 08:57:44

标签: spring-mvc cookies

我有一个在

上运行的现有Web应用程序
https://subdomain.example.com

现在我想要其他子域名

https://subdomain2.example.com

如何使用Spring MVC设置以下内容,以便在从第一个域重定向到第二个域后不会再次提示用户进行身份验证?

Set-Cookie: name=value; domain=example.com

1 个答案:

答案 0 :(得分:2)

请看这个控制器示例,但要记住两件事:

  • 如果您连接到127.0.0.1,则在本地环境中工作时,放置任意固定域将不允许您访问cookie。
  • 您的cookie可以被该主机(example.com)上的所有子域读取,而不仅仅是您想要的那些子域。

类别:

package com.test.foo;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/foo")
public class FooController {

    @RequestMapping("/cookie")
    public String setCookie(HttpServletRequest request, HttpServletResponse response)  {
        String value = "value";
        Cookie cookie = new Cookie("name", value);
        cookie.setPath("/");//<-- important
        cookie.setDomain("example.com");
        response.addCookie(cookie);
        return "foo/index";//your view
    }
}