java getCookies() 获取 cookie 和会话
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28632077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getCookies() gets both the cookies and the session
提问by Jessie
I have two servlets and the other servlet is supposed to output information from a cookie and from a session (instructions of our professor). The problem is, I tried using getCookies() to get cookies from the request object but it returns two objects the first one is with a name "JSESSIONID" and its accompanied hexadecimal code and the second one contains the cookie I created. Why did this happen? How would getCookie() solely return cookies?
我有两个 servlet,另一个 servlet 应该从 cookie 和会话(我们教授的指示)输出信息。问题是,我尝试使用 getCookies() 从请求对象中获取 cookie,但它返回两个对象,第一个是名称“JSESSIONID”及其附带的十六进制代码,第二个包含我创建的 cookie。为什么会这样?getCookie() 如何单独返回 cookie?
Here's the code:
这是代码:
Servlet 1:
小服务程序 1:
package com.telco.process;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ConvertServlet
*/
@WebServlet("/Convert")
public class ConvertServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String num;
private String telco;
private HttpSession session;
private RequestDispatcher rd;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String convertedNum = "";
session = request.getSession();
num = request.getParameter("number");
telco = request.getParameter("telco");
rd = request.getRequestDispatcher("Display");
Cookie cTelco = new Cookie("telco", telco);
if (!(num.equals(null)) || !(num.equals("")))
{
for (byte i = 0; i < num.length(); i++)
{
switch(num.charAt(i))
{
case 'A':
case 'B':
case 'C': convertedNum += "2"; break;
case 'D':
case 'E':
case 'F': convertedNum += "3"; break;
case 'G':
case 'H':
case 'I': convertedNum += "4"; break;
case 'J':
case 'K':
case 'L': convertedNum += "5"; break;
case 'M':
case 'N':
case 'O': convertedNum += "6"; break;
case 'P':
case 'Q':
case 'R':
case 'S': convertedNum += "7"; break;
case 'T':
case 'U':
case 'V': convertedNum += "8"; break;
case 'W':
case 'X':
case 'Y':
case 'Z': convertedNum += "9"; break;
}
}
session.setAttribute("number", convertedNum);
response.addCookie(cTelco);
}
rd.forward(request, response);
}
}
Servlet 2:
小服务程序 2:
package com.telco.process;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Display")
public class DisplayNumber extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Cookie ck[] = request.getCookies();
System.out.println(ck[0].getValue());
pw.println("The converted number is " + "-" + request.getSession(false).getAttribute("number"));
}
}
回答by Udo Klimaschewski
The JSESSIONID is indeed a cookie, it is used to identify the session. A session is created on the server with an ID. The server sends a cookie with the ID to the browser (JSESSIONID). The browser then sends this JSESSIONID cookie to the server on each request, where the server uses it to map the request to the session.
JSESSIONID 确实是一个 cookie,它用于识别会话。在服务器上创建一个带有 ID 的会话。服务器将带有 ID 的 cookie 发送到浏览器 (JSESSIONID)。然后,浏览器在每次请求时将此 JSESSIONID cookie 发送到服务器,服务器使用它来将请求映射到会话。
EDIT: Some example code to find a cookie:
编辑:一些用于查找 cookie 的示例代码:
You should access your cookies only by name, not by index. Here is an example helper routine, you can use it like this (of course, check for null
in a real program):
您应该仅通过名称而不是索引来访问您的 cookie。这是一个示例辅助程序,您可以像这样使用它(当然,请null
在实际程序中检查):
System.out.println(getCookieByName(request, "telco").getValue());
/**
* Find a specific HTTP cookie in a request.
*
* @param request
* The HTTP request object.
* @param name
* The cookie name to look for.
* @return The cookie, or <code>null</code> if not found.
*/
protected Cookie getCookieByName(HttpServletRequest request, String name) {
if (request.getCookies() == null) {
return null;
}
for (int i = 0; i < request.getCookies().length; i++) {
if (request.getCookies()[i].getName().equals(name)) {
return request.getCookies()[i];
}
}
return null;
}