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 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/SetCookieSet-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 servletcount++;Cookie counterCookie = new Cookie("Counter", String.valueOf(count));//add some description to be viewed in browser cookie viewercounterCookie.setComment("SetCookie Counter");//setting max age to be 1 daycounterCookie.setMaxAge(24*60*60);//set path to make it accessible to only this servletcounterCookie.setPath("/ServletCookie/cookie/SetCookie");//adding cookie to the responseresponse.addCookie(counterCookie);//set a domain specific cookieCookie 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 cookieif(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 ApplicationJava Web应用程序
  2. Servlet JSP TutorialServlet JSP教程
  3. Session Management in JavaJava中的会话管理
  4. Java Servlet FilterJava Servlet过滤器
  5. Servlet ListenerServlet侦听器
Download Servlet Cookie Example Project下载Servlet Cookie示例项目

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示例

jsp servlet示例_Java Servlet Cookies示例相关推荐

  1. java servlet 教程_Java Servlet完全教程

    Servlet 是一些遵从Java Servlet API的Java类,这些Java类可以响应请求.尽管Servlet可以响应任意类型的请求,但是它们使用最广泛的是响应web方面的请求. Servle ...

  2. java servlet原理_java servlet的工作原理是什么?

    展开全部 配置:编辑好的servlet源文件并不能响应用户请求,还必须将其编译成class文件,将编译好的class文件放到WEB-INF/classes路径下62616964757a68696461 ...

  3. java servlet 数据库_Java Servlet调用数据库复习

    首先要导入jar包. 剩下的基本就是模版式的代码了: public class main { // JDBC 驱动名及数据库 URL static final String JDBC_DRIVER = ...

  4. java 静态缓存示例_Java 9 JShell示例:集合静态工厂方法

    java 静态缓存示例 这篇文章继续从My My Java 9 Features博客文章中探索Java9功能. 在这里,我们在List,Set和Map接口中试验Java9 Collections静态工 ...

  5. java 方法 示例_Java扫描器具有示例的NextNextShort()方法

    java 方法 示例 扫描器类的hasNextShort()方法 (Scanner Class hasNextShort() method) Syntax: 句法: public boolean ha ...

  6. java 方法 示例_Java扫描仪具有示例的NextNextInt()方法

    java 方法 示例 扫描器类的hasNextInt()方法 (Scanner Class hasNextInt() method) Syntax: 句法: public boolean hasNex ...

  7. java 方法 示例_Java ArrayDeque带有示例的removeFirstOccurrence()方法

    java 方法 示例 ArrayDeque类removeFirstOccurrence()方法 (ArrayDeque Class removeFirstOccurrence() method) re ...

  8. 没有servlet接口_Java——Servlet

    在service方法里写后端的需要的处理.什么是Servlet? Servlet是运行在服务器端的小型应用程序,通过http接收和响应来自web客户端的请求. 2. 如何创建Servlet? 分为两步 ...

  9. java 上文件传示例_Java解压缩文件示例

    java 上文件传示例 Welcome to Java Unzip File Example. In the last post, we learned how to zip file and dir ...

最新文章

  1. php判断前端传的多个字段与数据库匹配
  2. 用Java创建JMeter变量 - 终极指南
  3. Matlab 中常用的直线与点形表示属性
  4. HDU 1568 Fibonacci【求斐波那契数的前4位/递推式】
  5. GDB调试多进程程序或同时调试多个程序
  6. Windows系统中使用SSH服务端和客户端
  7. 短信猫软件的实现(C#)九7bitPDU的编码
  8. axure6.5汉化
  9. matlab画圆函数
  10. USB转单串口、多串口芯片选型UART.TTL.RS-232等
  11. linux vi 拷贝多行,vi 整行 多行 复制与粘贴
  12. 机器学习相关问题与资源下载。
  13. 强连通分量分解详解 超级详细
  14. 前端vscode必备插件推荐(墙裂推荐)
  15. UI设计必备工具有哪些?
  16. halide 入门实战(1)
  17. 网络七层模型和对应协议的通俗理解
  18. VisualStudio找不到Python.h
  19. 离散系统的稳定性分析
  20. vuequilleditor编辑器的使用,字体无法对齐的问题

热门文章

  1. Android Studio 技巧
  2. IOS创建静态库Cocoa Touch Static Library
  3. [转载] 不少Gate或Node运算子 的反向传播代码
  4. [转载] python numpy 子数组_Python学习笔记3:Numpy入门
  5. poi报表导出4.1.0版本工具类 导出并下载
  6. 自然语言处理真实项目实战(20170822)
  7. JavaSE 学习笔记之正则表达式(二十五)
  8. Eclipse 常用快捷键和使用技巧
  9. 利用UICollectionView实现瀑布流
  10. 上周热点回顾(11.11-11.17)