jsp servlet示例_Java Servlet Cookies示例

jsp servlet示例

Welcome to Java Servlet Cookies example. Cookies are used a lot in web client-server communication, it’s not something specific to java.

欢迎使用Java Servlet Cookies示例。 Cookie在Web客户端与服务器之间的通信中被大量使用,它不是Java特有的。

Some of the common usage of cookies are:

Cookies的一些常见用法是:

  1. Session authentication using Cookies, we learned in Servlet Session Tutorial that HttpSession uses “JSESSIONID” cookie to keep track of the user session.

    通过使用Cookie进行会话身份验证,我们在Servlet会话教程中了解到HttpSession使用“ JSESSIONID” cookie来跟踪用户会话。
  2. Personalized response to the client based on their preference, for example we can set background color as cookie in client browser and then use it to customize response background color, image etc.

    根据客户的喜好对客户进行个性化响应,例如,我们可以在客户浏览器中将背景颜色设置为cookie,然后使用它自定义响应背景颜色,图像等。

Java Servlet中的Cookie (Cookies in Java Servlet)

cookies in java, cookies in servlet, java cookie example

Cookies are text data sent by server to the client and it gets saved at the client local machine. When client send request to server, it passes the cookies stored by the server in request header like below:


Cookies是服务器发送到客户端的文本数据,并保存在客户端本地计算机上。 客户端将请求发送到服务器时,它将服务器存储的cookie传递到请求标头中,如下所示:

Cookie	Test="Test Cookie5"

Client can send multiple cookies to server and we can disable cookies to get stored at client side from browser preferences. Apart from the key-value pairs, server sends some other data to client in response header and it looks something like below.

客户端可以向服务器发送多个cookie,并且我们可以禁用cookie以根据浏览器首选项存储在客户端。 除了键值对之外,服务器还会在响应标头中向客户端发送其他一些数据,如下所示。

Set-Cookie	Counter=7;
Version=1;
Comment="SetCookie Counter";
Domain="localhost";
Max-Age=86400;
Expires=Thu, 15-Aug-2013 20:19:19 GMT;
Path=/cookie/SetCookie

Set-Cookie	Test="Test Cookie7";
Version=1;
Comment="Test Cookie"

Note that server sends some additional information for cookie, such as comment, domain, maximum time before cookie expires and Path where browser should send the cookie back in request. But when client sends cookie to browser, it only sends the name and value of the cookie.

请注意,服务器会为cookie发送一些其他信息,例如注释,域,cookie过期之前的最长时间以及浏览器应在请求中将cookie发送回的路径。 但是,当客户端向浏览器发送cookie时,它仅发送cookie的名称和值。

Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.

Servlet API通过实现Serializable和Cloneable接口的javax.servlet.http.Cookie类提供cookie支持。

HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.

提供了HttpServletRequest getCookies()方法来从请求中获取Cookie数组,因为没有必要向请求中添加Cookie,所以没有方法可以设置或向请求中添加Cookie。

Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

类似地,提供了HttpServletResponse addCookie(Cookie c)方法来将cookie附加到响应头中,没有用于cookie的getter方法。

Cookie class has a single constructor that takes name and value because they are mandatory parameters for a cookie, all other parameters are optional.

Cookie类具有一个使用名称和值的构造函数,因为它们是cookie的必需参数,所有其他参数都是可选的。

Some important methods of Cookie class are:

Cookie类的一些重要方法是:

  1. getComment() – Returns the comment describing the purpose of this cookie, used at client side. Note that server doesn’t receive this information when client sends cookie in request header. We can use setComment() method to set cookie description at server side.

    getComment() –返回在客户端使用的描述此cookie用途的注释。 请注意,当客户端在请求标头中发送cookie时,服务器不会收到此信息。 我们可以使用setComment()方法在服务器端设置cookie描述。
  2. getDomain() – returns the domain name for the cookie. We can use setDomain() method to set the domain name for cookie, if domain name is set then the cookie will be sent only to that particular domain requests.

    getDomain() –返回cookie的域名。 我们可以使用setDomain()方法设置cookie的域名,如果设置了域名,则cookie仅发送到该特定域名请求。
  3. getMaxAge() – returns the maximum age in seconds. We can use setMaxAge() to set the expiration time of cookie.

    getMaxAge() –返回最长使用期限,以秒为单位。 我们可以使用setMaxAge()设置cookie的过期时间。
  4. getName() – returns the name of the cookie, can be used at both browser and server side. There is no setter for name, we can set name once through constructor only.

    getName() –返回cookie的名称,可在浏览器和服务器端使用。 名称没有设置器,我们只能通过构造函数设置名称一次。
  5. getPath() – Returns the path on the server to which the browser returns this cookie. We will see it’s example where the cookie will be sent to specific resource only. We can use setPath() to instruct browser to send cookie to a particular resource only.

    getPath() –返回浏览器将此cookie返回到的服务器上的路径。 我们将看到仅将Cookie发送到特定资源的示例。 我们可以使用setPath()指示浏览器仅将cookie发送到特定资源。
  6. getSecure() – Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol. We can use setSecure() method to instruct browser to send cookie only over secured protocol.

    getSecure() –如果浏览器仅通过安全协议发送cookie,则返回true;如果浏览器可以使用任何协议发送cookie,则返回false。 我们可以使用setSecure()方法来指示浏览器仅通过安全协议发送cookie。
  7. getValue() – returns the value of the cookie as String. There is also setValue() method to change the value of cookie.

    getValue() –以字符串形式返回cookie的值。 还有setValue()方法来更改cookie的值。
  8. getVersion() – Returns the version of the protocol this cookie complies with. There is also a setter method for version.

    getVersion() –返回此cookie遵循的协议的版本。 还有一个版本的设置方法。
  9. isHttpOnly() – Checks whether this Cookie has been marked as HttpOnly. There is also a setter method that we can use to instruct client to use it for HTTP only.

    isHttpOnly() –检查此Cookie是否已标记为HttpOnly。 还有一个setter方法,我们可以用来指示客户端仅将其用于HTTP。

Java Servlet Cookie示例 (Java Servlet Cookie Example)

We will create two simple servlets to print cookies from client, in one of the servlet we will set a cookie for every domain and a cookie with Path settings so that other servlet won’t receive this from client.

我们将创建两个简单的servlet,以从客户端打印cookie,在其中一个servlet中,我们将为每个域设置一个cookie,并为Path设置一个cookie,以便其他servlet不会从客户端接收到它。

Our final project structure for cookies in java servlet will look like below image.

下图是Java Servlet中Cookie的最终项目结构。

SetCookie.java: This servlet will set some cookies and send it to browser. It will also print cookie information and send it as HTML response.

SetCookie.java :此servlet将设置一些cookie并将其发送到浏览器。 它还将打印cookie信息并将其作为HTML响应发送。

package com.journaldev.servlet.cookie;

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;

@WebServlet("/cookie/SetCookie")
public class SetCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static int count = 0;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		Cookie[] requestCookies = request.getCookies();
		
		out.write("<html><head></head><body>");
		out.write("<h3>Hello Browser!!</h3>");
		if(requestCookies != null){
		out.write("<h3>Request Cookies:</h3>");
		for(Cookie c : requestCookies){
			out.write("Name="+c.getName()+", Value="+c.getValue()+", Comment="+c.getComment()
					+", Domain="+c.getDomain()+", MaxAge="+c.getMaxAge()+", Path="+c.getPath()
					+", Version="+c.getVersion());
			out.write("<br>");
		}
		}
		//Set cookies for counter, accessible to only this servlet
		count++;
		Cookie counterCookie = new Cookie("Counter", String.valueOf(count));
		//add some description to be viewed in browser cookie viewer
		counterCookie.setComment("SetCookie Counter");
		//setting max age to be 1 day
		counterCookie.setMaxAge(24*60*60);
		//set path to make it accessible to only this servlet
		counterCookie.setPath("/ServletCookie/cookie/SetCookie");

		//adding cookie to the response
		response.addCookie(counterCookie);
		
		//set a domain specific cookie
		Cookie domainCookie = new Cookie("Test", "Test Cookie"+String.valueOf(count));
		domainCookie.setComment("Test Cookie");
		response.addCookie(domainCookie);
		
		out.write("</body></html>");
	}

}

GetCookie.java: A simple servlet that will demonstrate that the cookie set in SetCookie with specific Path will not be send by browser to this servlet.

GetCookie.java :一个简单的Servlet,它将演示浏览器不会将SetCookie中具有特定Path设置的cookie发送到该servlet。

package com.journaldev.servlet.cookie;

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;

@WebServlet("/cookie/GetCookie")
public class GetCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		Cookie[] requestCookies = request.getCookies();
		
		out.write("<html><head></head><body>");
		out.write("<h3>Hello Browser!!</h3>");
		if(requestCookies != null){
		out.write("<h3>Request Cookies:</h3>");
		for(Cookie c : requestCookies){
			out.write("Name="+c.getName()+", Value="+c.getValue()+", Comment="+c.getComment()
					+", Domain="+c.getDomain()+", MaxAge="+c.getMaxAge()+", Path="+c.getPath()
					+", Version="+c.getVersion());
			out.write("<br>");
			//delete cookie
			if(c.getName().equals("Test")){
				c.setMaxAge(0);
				response.addCookie(c);
			}
		}
		}
		out.write("</body></html>");
	}

}

When you will run the program, you will notice few things:

当您运行该程序时,您会注意到一些事情:

  • Cookie “Counter” is sent over to the SetCookie only, GetCookie will never receive this cookie.

    Cookie“ Counter”仅发送到SetCookie,GetCookie将永远不会收到此Cookie。
  • Except name and value all other variables are printing default values. MaxAge default value is -1 and version default value is 0.

    除名称和值外,所有其他变量都在打印默认值。 MaxAge的默认值为-1,版本的默认值为0。
  • GetCookie is setting max age of “Test” cookie to 0, so that it will be expired and deleted by client browser.

    GetCookie将“测试” cookie的最长期限设置为0,这样它将被客户端浏览器过期并删除。

That’s all for cookies in java and it’s usage in Servlet API, you might want to check out other servlet tutorials too.

这就是Java中的cookie以及Servlet API中的用法,您可能还想查看其他servlet教程。

  1. Java Web Application

    Java Web应用程序
  2. Servlet JSP Tutorial

    Servlet JSP教程
  3. Session Management in Java

    Java中的会话管理
  4. Java Servlet Filter

    Java Servlet过滤器
  5. Servlet Listener

    Servlet侦听器

Check out next articles in series about Servlet Exception Handling and Servlet File Upload Download Example.

查阅有关Servlet异常处理Servlet文件上传下载示例系列的下一篇文章。

翻译自: https://www.journaldev.com/1956/java-servlet-cookies-example

jsp servlet示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值