无法在spring-boot应用程序中存储/检索cookie

时间:2014-12-28 20:44:35

标签: java spring cookies

在我目前的spring-boot项目中,我添加了这个类,目的是允许我存储和检索cookie:

public class CookieAcessor {
  public static List<HttpCookie> getCookies() {
    try {
      CookieManager manager = new CookieManager();
      manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
      CookieHandler.setDefault(manager);
      CookieStore cookieJar =  manager.getCookieStore();
      URL url = new URL("http://localhost:8080");
      List <HttpCookie> cookies = cookieJar.get(url.toURI());
      return cookies;
    } catch(Exception e) {
      return new ArrayList<HttpCookie>();
    }
  }

  public static String getCookie(String key) {
    List<HttpCookie> cookies = getCookies();
    for(HttpCookie cookie : cookies) {
      if(cookie.getName().equals(key))
        return cookie.getValue();
    }
    return null;
  }

  public static void setCookie(String key, String value) {
    try {
      CookieManager manager = new CookieManager();
      CookieHandler.setDefault(manager);
      CookieStore cookieJar =  manager.getCookieStore();
      HttpCookie cookie = new HttpCookie(key, value);
      URL url = new URL("http://localhost:8080");
      cookieJar.add(url.toURI(), cookie);
    } catch(Exception e) {
      System.out.println("Erro ao armazenar o cookie!");
    }
  }
}

但是当我尝试执行此类中的任何方法(用于读取或保存cookie)时,什么也没做。任何人都可以看到这段代码有什么问题?它基于官方文档中的这篇文章:http://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html

更新

此类用于来自控制器的方法,如下所示:

  @RequestMapping(value = "/")
  public String index() {
    CookieAcessor.setCookie("teste", "...");
    System.out.println("cookie[teste] = "+CookieAcessor.getCookie("teste"));
    return "public/index";
  }

0 个答案:

没有答案