在java servlet中我有以下代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("tom_cookies",Long.toString(new Date().getTime()));
cookie.setMaxAge(30);
cookie.setPath(request.getContextPath());
cookie.setComment("1");
cookie.setVersion(1);
System.out.println("Cookie created!");
response.addCookie(cookie);
}
在 JSP index.jsp 中我有以下代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MyIndex</title>
</head>
<body>
<div>CookieComment: <%
Cookie[] my = request.getCookies();
for(int i=0;i<my.length;i++){
String comment = my[i].getComment();
out.println(comment);
}
%>
</div></body></html>
我的 web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<display-name>1aaa</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
在 local:8080/servlet 中,我期望的是这样的:
CookieComment: 1
但是,它只显示:
CookieComment: null
这里出了什么问题?
最佳答案
您实际上并不需要通过 scriptlet 代码从请求对象获取 cookie,您可以通过 EL 使用名为“cookie”的隐式变量
${cookie.yourCookieName}
这应该在 JSP 页面中打印您的 cookie 值。它在响应对象中查找 cookie
希望对你有帮助
关于java servlet在JSP中获取cookie值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36096904/