Servlet无法为客户端的第一个请求发送cookie

时间:2015-03-04 12:52:43

标签: java servlets cookies

我想创建一个cookie,它保持客户端持久存储的访问次数,我的服务器是在Apache Tomcat 8.0上运行的简单servlet,

  • 当客户端发送一个已经用计数器初始化的cookie时(例如counter = 12),服务器递增计数器并发回新cookie与新计数器(counter = 13)并由客户端在我的硬盘上正确保存。这对我来说很好。
  • 但是当客户端第一次发送请求时,所以没有cookie发送到服务器,服务器应该创建一个counter = 0的新cookie并将其发送回客户端。此案例无法正常运行,客户端未收到任何cookie。

这是我的代码示例:

客户端

public class Test
{
    URI uri;
    HttpURLConnection httpCon;

    public static String urlString = "http://localhost:8082/Test/ReverseServlet";

    public Test()
    {
        CookieManager cookieManager = new CookieManager(new MyCookieStore(), CookiePolicy.ACCEPT_ALL);
        CookieManager.setDefault(cookieManager);
        try
        {
            try
            {
                uri = new URI(urlString);
            }
            catch (URISyntaxException e)
            {
                e.printStackTrace();
            }
            httpCon = (HttpURLConnection) uri.toURL().openConnection();


                if (cookieManager.getCookieStore().get(uri).size() > 0)
                {
                    httpCon.setRequestProperty("Cookie", cookieManager.getCookieStore().get(uri).get(0).toString());
                }

            httpCon.connect();

            Map<String, List<String>> headerFields = httpCon.getHeaderFields();
            List<String> cookiesHeader = headerFields.get("Set-Cookie");

            if (cookiesHeader != null)
            {
                for (String cookie : cookiesHeader)
                {
                    cookieManager.getCookieStore().add(uri, HttpCookie.parse(cookie).get(0));
                }
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        new Test();
    }
}

class MyCookieStore implements CookieStore
{
    CookieStore store;
    Path pathCookiesStore;
    URI uri;

    public MyCookieStore()
    {
        try
        {
            pathCookiesStore = Paths.get("D:\\Temp\\cookies.txt");
            if (!Files.exists(pathCookiesStore))
            {
                Files.createFile(pathCookiesStore);
            }
            try
            {
                uri = new URI(Test.urlString);
            }
            catch (URISyntaxException e1)
            {
                e1.printStackTrace();
            }
            List<String> cookies = Files.readAllLines(pathCookiesStore);
            store = new CookieManager().getCookieStore();
            if (cookies.size() > 0)
            {
                HttpCookie countCookie = new HttpCookie("count", cookies.get(0));
                countCookie.setDomain("localhost.local");
                countCookie.setMaxAge(-1);
                countCookie.setPath("/Test/");
                store.add(uri, countCookie);
            }

            Runtime.getRuntime().addShutdownHook(new Thread()
            {
                public void run()
                {
                    try
                    {
                        PrintWriter pw = new PrintWriter(new OutputStreamWriter(Files.newOutputStream(pathCookiesStore, StandardOpenOption.WRITE,
                                StandardOpenOption.TRUNCATE_EXISTING)));
                        for (HttpCookie cookie : store.getCookies())
                        {
                            if (cookie.getName().equals("count"))
                            {
                                pw.println(cookie.getValue());
                                pw.flush();
                                pw.close();
                                break;
                            }
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
        catch (IOException excp)
        {
            excp.printStackTrace();
        }
    }

    public void add(URI uri, HttpCookie cookie)
    {
        store.add(uri, cookie);
    }

    public List<HttpCookie> get(URI uri)
    {
        return store.get(uri);
    }

    public List<HttpCookie> getCookies()
    {
        return store.getCookies();
    }

    public List<URI> getURIs()
    {
        return store.getURIs();
    }

    public boolean remove(URI uri, HttpCookie cookie)
    {
        return store.remove(uri, cookie);
    }

    public boolean removeAll()
    {
        return store.removeAll();
    }
}

服务器

public class ReverseServlet extends HttpServlet
{
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    {
        int countVisits = 0;
        Cookie cookies[] = req.getCookies();
        if (cookies.length > 0)
        {
            for (Cookie cookie : cookies)
            {
                if (cookie.getName().equals("count"))
                {
                    try
                    {
                        countVisits = Integer.parseInt(cookie.getValue());
                        countVisits++;
                    }
                    catch (NumberFormatException excp)
                    {
                        countVisits = 0;
                    }
                    break;
                }
            }
        }
        Cookie countCookie = new Cookie("count", String.valueOf(countVisits));
        countCookie.setDomain("localhost.local");
        countCookie.setMaxAge(-1);
        countCookie.setPath("/Test/");
        resp.addCookie(countCookie);
    }
}

0 个答案:

没有答案