我有以下问题:我有一些JSP页面。 当我在主页面上时,我可以添加Cookie。 在CookieAdd页面中,我添加了一个Cookie并使用jsp:forward重定向到主页面。 然后添加的Cookie应该显示,但它不会立即显示。 我必须重新加载页面才能看到新添加的cookie。 我怎么能立刻看到它? 谢谢,汤姆。
<% Cookie c = new Cookie(request.getParameter("name"), ""); c.setMaxAge(0); response.addCookie(c); %> <% Cookie c = new Cookie(request.getParameter("name"), ""); c.setMaxAge(0); response.addCookie(c); %> <html> <body>
`<jsp:forward page="Cookiemanager.jsp" />`</body> </html>
I have the following problem: I have a few JSP pages. When I am on the main page I have the possibility to add a Cookie. In the CookieAdd page I add a Cookie and redirect myself with jsp:forward to the main page. Then the added Cookie should show up, but it doesn't show up immediatly. I have to reload the page to see the newly added cookie. How can I see it immediatly? Thanks, Tom.
<% Cookie c = new Cookie(request.getParameter("name"), ""); c.setMaxAge(0); response.addCookie(c); %> <html> <body>
`<jsp:forward page="Cookiemanager.jsp" />`</body> </html>
最满意答案
您没有重定向到主页面。 您将转发到主页面。 转发完全发生在服务器端。 服务器没有收到任何新请求:相同的原始请求只是由另一个JSP处理。 因此,当第二个JSP处理相同的请求时,原始请求中不存在的cookie仍然不存在。
重定向完全不同。 重定向包括要求浏览器转到另一个URL。 如果您这样做,那么浏览器将接收cookie作为重定向响应的一部分,然后将新的请求(包含cookie)发送到新JSP。
请注意,您发布的代码不应该在JSP中。 JSP是一个视图组件。 它的目标不是设置cookie或转发/重定向。 它的目标是生成HTML。 这样的代码应该在用Java编写的servlet中。
You're not redirecting to the main page. You're forwarding to the main page. Forwarding happens completely at server-side. No new request is received by the server: the same, original request is simply handled by another JSP. So the cookie, that was not there in the original request, si still not there when this same request is handled by the second JSP.
A redirect is completely different. Redirecting consists in asking the browser to go to another URL. If you did that, then the browser would receive the cookie as part of the redirect response, and would then send a new request, containing the cookie, to the new JSP.
Note that the code you posted should not be in a JSP. A JSP is a view component. Its goal is not to set cookie or forward/redirect. Its goal is to generate HTML. Such code should be in a servlet, written in Java.
更多推荐
发布评论