Servlet是Java EE非常重要的主题,所有的 Web 应用程序框架(如Spring和Struts)都建立在它之上。这使得 servlet 面试在面试中成为一个热门话题。
在这里,我提供了一个包含 50 个 servlet 面试问题的列表,其中包括解答大部分与 java 中的 servlet 和 web 应用程序有关的面试问题。
A web server responsibility is to handler HTTP requests from client browsers and respond with HTML response. A web server understands HTTP language and runs on HTTP protocol.
Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat.
Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications.
Web 服务器的职责是处理来自客户端浏览器的 HTTP request,并用 HTML response 进行响应。Web 服务器了解 HTTP 语言并运行在 HTTP 协议之上。
Apache Web Server 是一种 Web 服务器,我们有特定的可以执行 servlet 和 JSP 的容器,就是 servlet 容器,栗如 Tomcat
应用程序服务器提供了额外的功能,栗如 Enterprise JavaBeans 支持, JMS 消息传递支持,事务管理等。所以我们可以说 Application Server 是一个具有附加功能的 Web 服务器,可以帮助开发人员使用企业应用程序。
A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.
如果 HTTP 方法每次返回相同的结果,就说它是幂等的。HTTP 方法 GET、PUT、DELETE、HEAD 和 OPTIONS 是幂等方法,我们应该实现我们的应用程序来确保这些方法始终返回相同的结果。HTTP 方法 POST 是非幂等方法,我们应该使用 POST 方法来实现随每个请求而改变的东西。
The “Content-Type” response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.
We can use ServletContext getMimeType() method to get the correct MIME type of the file and use it to set the response content type. It’s very useful in downloading file through servlet from server.
“Content-Type”response header 被称为MIME类型。服务器发送MIME类型给客户端,让他们知道它发送的数据的种类。 它帮助客户为用户呈现数据。一些最常用的MIME类型有text/html
、text/xml
和application/xml
等。
我们可以使用ServletContext
的getMimeType()
方法获取文件的正确的MIME类型,并使用它来 response content 类型。从服务器通过 servlet 下载文件时非常有用。
Web Applications are modules that run on server to provide both static and dynamic content to the client browser. Apache web server supports PHP and we can create web application using PHP. Java provides web application support through Servlets and JSPs that can run in a servlet container and provide dynamic content to client browser.
Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure like below image.
Read more about web applications at Java Web Application.
Web 应用程序是服务器上用于向客户端提供静态和动态内容的模块。Apache Web 服务器支持 PHP,我们可以使用 PHP 创建 Web 应用程序。Java 通过在 servlet 容器中运行 Servlet 和 JSP 提供 Web 应用程序支持,并向客户端浏览器提供动态内容。
Java Web 应用程序打包为 Web Archive(WAR),并具有如下图所示的定义的结构
在Java Web Application 上阅读更多关于 Web 应用程序的信息。
Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.
Read more at Servlet Tutorial.
Java Servlet 是服务器端技术,通过提供动态响应和护具持久的支持来扩展 Web 服务器的功能。
java.servlet
和 javax.servlet.http
包提供了编写我们自己的 servlet 的接口和类。
所有的 servlet 必须实现 java.servlet.Servlet
接口,该接口定义了 servlet 的生命周期方法。在实现通用服务时,我们可以扩展 Java Servlet API 提供的 GenericServlet
类。HttpServlet
类提供了用于处理特定 HTTP 服务的方法,如doGet()
和doPost()
。
大多数情况下,Web 应用程序是使用 HTTP 协议访问的,这就是为什么我们能主要扩展 HttpServlet 类的原因。Servlet API层次结构如下图所示。
阅读更多:Servlet Tutorial.
Servlet technology was introduced to overcome the shortcomings of CGI technology.
引入了 Servlet 技术来克服 CGI 技术的缺点。
Servlet containers are also known as web container, for example Tomcat. Some of the important tasks of servlet container are:
Communication Support
: Servlet Container provides easy way of communication between web client (Browsers) and the servlets and JSPs. Because of container, we don’t need to build a server socket to listen for any request from web client, parse the request and generate response. All these important and complex tasks are done by container and all we need to focus is on business logic for the applications.Lifecycle and Resource Management
: Servlet Container takes care of managing the life cycle of servlet. From the loading of servlets into memory, initializing servlets, invoking servlet methods and to destroy them. Container also provides utility like JNDI for resource pooling and management.Multithreading Support
: Container creates new thread for every request to the servlet and provide them request and response objects to process. So servlets are not initialized for each request and saves time and memory.JSP Support
: JSPs doesn’t look like normal java classes but every JSP in the application is compiled by container and converted to Servlet and then container manages them like other servlets.Miscellaneous Task
: Servlet container manages the resource pool, perform memory optimizations, execute garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.Servlet 容器也被称为 Web 容器,例如Tomcat。一些 servlet 容器的重要任务有:
Communication Support(通信支持)
:Servlet 容器提供了简单的 Web 客户端(浏览器)与 servlet 和 JSP 之间的通信方式。由于容器的原因,我们不需要构建 server socket(服务器套接字)来监听来自 Web 客户端的请求,解析请求并生成响应。所有这些重要而复杂的任务都是通过容器完成的,我们需要关注的只是应用程序的业务逻辑。Lifecycle and Resource Management(生命周期和资源管理)
:Servlet Container 负责管理 servlet 的生命周期。从将servlet 加载到内存中,初始化 servlet,调用 servlet 方法并销毁它们。容器也提供像 JNDI 这样的工具来进行资源池和管理。Multithreading Support(多线程支持)
:Container 为 servlet 的每个请求创建一个新线程,并为它们提供 request 和response 对象进行处理。所以 servlet 不会为每个请求初始化,并节省时间和内存。JSP Support(JSP支持)
:JSP 看起来不像普通的 Java 类,但应用程序中的每个 JSP 都是由容器编译并转换为 Servlet,然后容器像其他 servlet 一样管理它们。Miscellaneous Task(杂项任务)
:Servlet 容器管理资源池,执行内存优化,执行垃圾回收器,提供安全配置,支持多个应用程序,热部署和场景后面的几个其他任务,使开发人员生活变得更容易。javax.servlet.ServletConfig
is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig
object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam
annotation. We can use getServletConfig()
method to get the ServletConfig object of the servlet.
javax.servlet.ServletConfig
被用于将配置信息传递给 Servle。每个 servlet 都有自己的 ServletConfig 对象,servlet 容器负责实例化这个对象。我们可以在web.xml
文件中提供 Servlet 初始化参数,也可以使用 WebInitParam
注解。我们可以使用getServletConfig()
方法类获取 Servlet 的ServletConfig
对象。
javax.servlet.ServletContext
interface provides access to web application parameters to the servlet. The ServletContext
is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext
object and define parameters in web.xml using
element. We can get the ServletContext
object via the getServletContext()
method of ServletConfig
. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.
ServletContext
is enhanced in Servlet Specs 3
to introduce methods through which we can programmatically add Listeners
and Filters
and Servlet
to the application. It also provides some utility methods such as getMimeType()
, getResourceAsStream()
etc.
javax.servlet.ServletContext
接口提供对 servlet 的 Web 应用程序参数的访问。ServletContext
是可用于 Web 应用程序中所有的 servlet 的唯一的对象。当我们想要一些初始化参数可用于 Web 应用程序中的多个或所有 servlet 时,我们可以使用ServletContext
对象并使用
元素在 web.xml
中定义参数。我们可以通过ServletConfig
的getServletContext()
方法获取ServletContext
对象。Servlet 容器还提供 context 对象,这些 context 对象对于一组 servlet 时唯一的。并且绑定到主机的 URL 路径名称空间的特定部分。
Servlet Specs 3 中增强了ServletContext
,以引入方法,同故宫这些方法我们可以以编程方式将Listener
和Filters
以及Servlet
添加到应用程序中。它还提供了一些实用的方法,如getMimeType()
、getResourceAsStream()
等。
Some of the differences between ServletConfig
and ServletContext
are:
ServletConfig
is a unique object per servlet whereas ServletContext is a unique object for complete application.ServletConfig
is used to provide init parameters to the servlet whereas ServletContext
is used to provide application level init parameters that all other servlets can use.ServletConfig
object whereas we can set attributes in ServletContext
that other servlets can use in their implementation.ServletConfig 和 ServletContext 之间的区别有:
ServletConfig
是每个 servlet 的唯一对象。ServletContext
是整个应用程序的唯一对象。ServletConfig
用于给 servlet 提供 init parameters。ServletContext
用于提供应用程序级别的可供所有其他 servlet使用的 init parameters。RequestDispatcher
interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.
There are two methods defined in this interface:
1. void forward(ServletRequest request, ServletResponse response)
– forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
2. void include(ServletRequest request, ServletResponse response)
– includes the content of a resource (servlet, JSP page, HTML file) in the response.
3. We can get RequestDispatcher
in a servlet using ServletContext
getRequestDispatcher(String path)
method. The path must begin with a / and is interpreted as relative to the current context root.
RequestDispatcher
接口是用于将请求转发到另一个资源的,该资源可以是同一应用程序中的 HTML、JSP 或其他 servlet。我们也可以使用这个来将其他资源的内容包含到 response 中。该接口用于在相同上下文中进行 内部 servlet 通信。
这个接口定义了两个方法:
1. void forward(ServletRequest request, ServletResponse response)
– 将请求从 servlet 转发到服务器上的另一个资源。
2. void include(ServletRequest request, ServletResponse response)
– 在响应中包含资源(servlet、JSP 页面、HTML 文件)
3. 我们在 servlet 中可以使用ServletContext
、getRequestDispatcher(String path)
方法来获得RequestDispatcher
。该路径必须以“/”开始,并解释为相对于当前上下文跟。
PrintWriter
is a character-stream class whereas ServletOutputStream
is a byte-stream class. We can use PrintWriter
to write character based information such as character array and String to the response whereas we can use ServletOutputStream
to write byte array data to the response.
We can use ServletResponse
getWriter()
to get the PrintWriter
instance whereas we can use ServletResponse getOutputStream()
method to get the ServletOutputStream
object reference.
You can read more about IO in java at Java IO Tutorial.
PrintWriter
是字符流类,而ServletOutputStream
是字节流类。我们可以使用PrintWriter
将基于字符的信息(如字符数组和字符串)写入 response,而我们使用ServletOutputStream
将字节数组数据写入 response。
可以使用ServletResponse
的getWriter()
获取PrintWriter
实例。使用ServletResponse
的getOutputStream()
方法获取ServletOutputStream
对象的引用。
你可以在Java IO Tutorial上阅读更多关于 IO 的信息。
We can’t get instances of both PrintWriter
and ServletOutputStream
in a single servlet method, if we invoke both the methods; getWriter()
and getOutputStream()
on response; we will get java.lang.IllegalStateException
at runtime with message as other method has already been called for this response.
如果我们调用两个方法,不能在一个 servlet 中同时获取PrintWriter
和ServletOutputStream
的实例;getWriter()
和getOutputStream()
作为响应;我们将在运行时得到java.lang.IllegalStateException
消息,其他方法已经为响应被调用。
We can create deadlock in servlet by making a loop of method invocation, just call doPost() method from doGet() method and doGet() method to doPost() method to create deadlock situation in servlet.
Read more about deadlock in multithreading at Java Deadlock Example.
我们可以通过创建一个方法调用的循环来创建 servlet 死锁,只要从doGet()
方法调用doPost()
方法,doPost()
方法调用doGet()
方法在 servlet 中创建死锁情况。
在 Java Deadlock Example 中阅读更多有关多线程死锁的信息。
Servlet HTTP API provides two wrapper classes – HttpServletRequestWrapper
and HttpServletResponseWrapper
. These wrapper classes are provided to help developers with custom implementation of servlet request and response types. We can extend these classes and override only specific methods we need to implement for custom request and response objects. These classes are not used in normal servlet programming.
Servlet HTTP API 提供两个包装类 - HttpServletRequestWrapper
和HttpServletResponseWrapper
。提供这些包装类是为了帮助开发人员定制实现 servlet 请求和响应类型。我们可以扩展这些类并重写我们需要为自定义请求和响应对象实现的特定方法。这些类不用于通常的 servlet 编程。
SingleThreadModel
interface was provided for thread safety and it guarantees that no two threads will execute concurrently in the servlet’s service method. However SingleThreadModel
does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel
servlets are used. Also it takes out all the benefits of multithreading support of servlets, thats why this interface is Deprecated in Servlet 2.4.
SingleThreadModel
接口是为了线程安全而提供的,它保证 servlet 的服务方法中不会同时执行两个线程。但是SingleThreadModel
并不能解决所有的线程安全问题。栗如,即使在使用SingleThreadModel
servlet 的时候,会话属性和静态变量依旧可以被多个线程上的多个请求访问。同时它抵消了 servlet 的多线程支持的所有好处,这就是这个接口在 Servlet 2.4 被弃用的原因。
When servlet container receives client request, it invokes the service()
method which in turn invokes the doGet()
, doPost()
methods based on the HTTP
method of request. I don’t see any use case where we would like to override service() method. The whole purpose of service()
method is to forward to request to corresponding HTTP
method implementations. If we have to do some pre-processing of request, we can always use servlet filters and listeners.
当 servlet 容器收到客户端请求时,它会调用service()
方法,然后调用基于请求的 HTTP 方法的doGet()
、doPost()
方法。我没有看到任何我们想要重写service()
方法的用例。service()
方法的全部用途是转发请求到相应的 HTTP 方法实现。如果我们需要做一些预处理请求,我们可以使用 servlet 过滤器和监听器。
We can define a constructor for servlet but I don’t think its of any use because we won’t be having access to the ServletConfig
object until unless servlet is initialized by container. Ideally if we have to initialize any resource for servlet, we should override init()
method where we can access servlet init parameters using ServletConfig
object.
我们为 servlet 可以定义一个构造器,但是我不认为它有任何用处,除非 servlet 被容器初始化,否则不能将不能访问ServletConfig
对象。理想情况下,如果我们必须初始化 servlet 的任何资源,我们应该重写init()
方法,在那里我们可以使用ServletConfig
对象来访问 Servlet 初始化参数。
GenericServlet
is protocol independent implementation of Servlet interface whereas HttpServlet
is HTTP protocol specific implementation. Most of the times we use servlet for creating web application and that’s why we extend HttpServlet
class. HttpServlet
class extends GenericServlet
and also provide some other methods specific to HTTP protocol.
GenericServlet
是 Servlet 接口的独立协议实现,而HttpServlet
是 HTTP 协议特定的实现。大多数情况下,我们使用 servlet 里创建 Web 应用程序,这就是我们扩展HttpServlet
类的原因。HttpServlet
类扩展了GenericServlet
,还提供了一些特定于 HTTP 协议的其他方法。
When we want to invoke another servlet from a servlet service methods, we use inter-servlet communication mechanisms. We can invoke another servlet using RequestDispatcher
forward()
and include()
methods and provide additional attributes in request for other servlet use.
当我们想要从一个 servlet 服务方法中调用另一个 servlet 时,我们使用了 servlet 间通信机制。我们可以使用RequestDispatcher
forward()
和include()
方法调用另一个 servlet,并在请求其他 servlet 时提供其他属性。
HttpServlet
init()
method and destroy()
method are called only once in servlet life cycle, so we don’t need to worry about their synchronization. But service methods such as doGet()
or doPost()
are getting called in every client request and since servlet uses multithreading, we should provide thread safety in these methods.
If there are any local variables in service methods, we don’t need to worry about their thread safety because they are specific to each thread but if we have a shared resource then we can use synchronization to achieve thread safety in servlets when working with shared resources.
The thread safety mechanisms are similar to thread safety in standalone java application, read more about them at Thread Safety in Java.
HttpServlet
的init()
方法和destroy()
方法在 servlet 声明周期中只会被调用一次。所以我们不要去担心它们的同步。但是诸如doGet()
或doPost()
等服务方法在每个客户端请求中都会被调用,并且由于 servlet 使用多线程,所以我们应该在这些方法中提供线程安全性。
如果服务方法中有任何局部变量,我们不必担心它们的线程安全性,因为它们是针对每个线程的,但是如果我们有一个共享的资源,那么在使用共享时,我们可以使用同步来实现 servlet 中的线程安全资源。
线程安全机制类似于独立 Java 应用程序中的线程安全性,在 Thread Safety in Java 中阅读更多内容。
Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes in web application. There are three scopes for servlet attributes – request scope, session scope and application scope.
ServletRequest
, HttpSession
and ServletContext
interfaces provide methods to get/set/remove attributes from request, session and application scope respectively.
Servlet attributes are different from init parameters defined in web.xml for ServletConfig
or ServletContext
.
Servlet 属性用于 servlet 间的通信,我们可以在 Web 应用程序中set、get 和 remove 属性。servlet 属性有三个范围 - request scope、session scope 和 application scope。
We can use RequestDispatcher
forward()
method to forward the processing of a request to another servlet. If we want to include the another servlet output to the response, we can use RequestDispatcher
include()
method.
我们可以使用RequestDispatcher
的forward()
方法来将请求处理转发给另一个 servlet。如果我们想要将另一个 servlet 输出包含到 response 中,我们可以使用RequestDispatcher
的include()
方法。
We can’t use RequestDispatcher
to invoke servlet from another application because it’s specific for the application. If we have to forward the request to a resource in another application, we can use ServletResponse
sendRedirect()
method and provide complete URL of another servlet. This sends the response to client with response code as 302 to forward the request to another URL. If we have to send some data also, we can use cookies that will be part of the servlet response and sent in the request to another servlet.
我们不能使用RequestDispatcher
从另一个程序中调用 servlet,因为它是特定于应用程序的。如果我们必须将请求转发到另一个应用程序中的资源,我们可以使用ServletResponse
的sendRedirect()
方法,并提供另一个 servlet 的完整 URL。这将 响应代码为 302 的 response 发送给客户端,将请求转发到另一个 URL。如果我们还要发送一些数据,我们可以使用 cookie 作为 servlet response 的一部分,并将请求发送到另一个 servlet。
RequestDispatcher
forward()
is used to forward the same request to another resource whereas ServletResponse
sendRedirect()
is a two step process. In sendRedirect()
, web application returns the response to client with status code 302 (redirect) with URL to send the request. The request sent is a completely new request.forward()
is handled internally by the container whereas sendRedirect()
is handled by browser.forward()
when accessing resources in the same application because it’s faster than sendRedirect()
method that required an extra network call.forward()
browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect()
URL in address bar change to the forwarded resource.forward()
can’t be used to invoke a servlet in another context, we can only use sendRedirect()
in this case.RequestDispatcher
的forward()
方法用来转发相同的请求到另一个资源,而ServletResponse
的sendRedirect()
方法则是一个两步的过程。在sendRedirect()
中,Web 应用程序使用 URL 向客户端返回具有 302 状态码的发送请求。这个请求将发送一个全新的请求。forward()
由容器内部处理,而sendRedirect()
由浏览器处理。forward()
,因为它比需要额外网络调用的sendRedirect()
方法要快。forward()
中,浏览器并不知道实际处理资源,地址栏的 URL 保持不变,而在sendRedirect()
中,URL 转换为转发的资源。forward()
不能用于在一个上下文中调用一个 servlet,这种情况下我梦只能使用sendRedirect()
。HttpServlet
class provide HTTP protocol implementation of servlet but it’s left abstract because there is no implementation logic in service methods such as doGet()
and doPost()
and we should override at least one of the service methods. That’s why there is no point in having an instance of HttpServlet
and is declared abstract class.
Read more about abstract class.
HttpServlet
类提供 servlet 的 HTTP 协议实现,但是由于在doGet()
和doPost()
这样的服务方法中没有实现逻辑,并且我们应该重写至少一个服务方法,所以它是抽象的。这就是为什么有一个HttpServlet
实例没有意义,被声明为抽象类的原因。
阅读更多关于 abstract class。
We know that Servlet Container manages the life cycle of Servlet, there are four phases of servlet life cycle.
ServletContext
object for the servlet and then invoke it’s init method by passing servlet config object. This is the place where a servlet class transforms from normal class to servlet.service()
method by passing the request and response object reference.destroy()
method.我们知道 Servlet 容器管理 Servlet 的生命周期,Servlet 生命周期有四个阶段。
ServletContext
对象,然后通过传递 servlet config 对象来调用它的 init 犯法。这是 servlet 类从普通类转换为 servlet 的地方。service()
方法。destroy()
方法来销毁 servlet 类。Servlet Life Cycle consists of three methods:
public void init(ServletConfig config)
– This method is used by container to initialize the servlet, this method is invoked only once in the lifecycle of servlet.public void service(ServletRequest request, ServletResponse response)
– This method is called once for every request, container can’t invoke service() method until unless init() method is executed.public void destroy()
– This method is invoked once when servlet is unloaded from memory.Servlet 生命周期包含三种方法:
public void init(ServletConfig config)
– 这个方法被容器调用来初始化 servlet,在 servlet 生命周期中只被调用一次。public void service(ServletRequest request, ServletResponse response)
– 对于每个请求,这个方法都将会被调用一次,除非init()
方法被执行,否则容器不能调用service()
方法。public void destroy()
– 当 servlet 从内存中卸载时,调用此方法一次。If we have to initialize some resource before we want our servlet to process client requests, we should override init()
method. If we override init(ServletConfig config)
method, then the first statement should be super(config)
to make sure superclass init(ServletConfig config)
method is invoked first. That’s why GenericServlet
provides another helper init()
method without argument that get’s called at the end of init(ServletConfig config)
method. We should always utilize this method for overriding init()
method to avoid any issues as we may forget to add super()
call in overriding init method with ServletConfig
argument.
如果我们想要我们的 servlet 在处理客户端请求之前必须初始化一些资源,我们应该重写init()
方法。如果我们重写init(ServletConfig config)
方法,那么第一个语句应该是super(config)
以确保首先调用超类的init()
方法。这就是为什么GenericServlet
提供了另一个助手 - 在init(ServletConfig config)
结束的时候调用的无参的init()
方法。我们应该总是使用这个方法来重写init()
方法来避免任何因为我们能在重写没有ServletConfig
参数的 init 方法时忘记添加super()
调用而产生的问题。
URL Encoding is the process of converting data into CGI form so that it can travel across the network without any issues. URL Encoding strip the white spaces and replace special characters with escape characters. We can use java.net.URLEncoder.encode(String str, String unicode)
to encode a String. URL Decoding is the reverse process of encoding and we can use java.net.URLDecoder.decode(String str, String unicode)
to decode the encoded string. For example “Pankaj’s Data” is encoded to “Pankaj%27s+Data”.
URL Encoding 是将数据转换为 CGI 格式的过程,以便它可以在网络上传输,而不会出现任何问题。URL 编码去掉空格并用转义字符替换特殊字符。我们可以使用java.net.URLEncoder.encode(String str, String unicode)
来编码一个 String。URL 解码时编码的逆向过程,我们可以使用java.net.URLDecoder.decode(String str, String unicode)
来解码编码的字符串。栗如例如“Pankaj’s Data”被编码为“Pankaj%27s + Data”。
Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.
Some of the common ways of session management in servlets are:
Read more about these session management approaches in detail at Servlet Session Management Tutorial.
会话是客户端和服务器之间的转换状态,它可以由客户端和服务器之间的多个 request 和 response 组成。由于 HTTP 和 Web 服务器都是无状态的,因此维护会话的唯一方法是在每个 request 和 response 中,在服务器和客户端支架传递有关会话(会话ID)的一些唯一信息。
servlet 中会话管理的一些常见方式是:
在 Servlet Session Management Tutorial 中了解这些会话管理方法。
We can use HttpSession
for session management in servlets but it works with Cookies
and we can disable the cookie in client browser. Servlet API provides support for URL rewriting that we can use to manage session in this case.
The best part is that from coding point of view, it’s very easy to use and involves one step – encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback approach and it kicks in only if browser cookies are disabled.
We can encode URL with HttpServletResponse
encodeURL()
method and if we have to redirect the request to another resource and we want to provide session information, we can use encodeRedirectURL()
method.
Read More at Servlet URL Rewriting.
我们可以在 Servlet 中使用HttpSession
进行会话管理,但是它需要与 Cookies 协同工作,我们可以在客户端浏览器中禁用 Cookie。这种情况下 Servlet API 提供了对 URL 重写的支持,我们可以使用它来管理会话。
最棒的是从编码的角度来看,只需要一个步骤 - 对 URL 进行编码。Servlet URL Encoding 的另一个好处是它是一个备用方法,只有在历览器 cookies 被禁用的情况下才会启动。
我们可以使用HttpServletResponse
的encodeURL()
方法编码 URL,如果我们必须将请求重定向到另一个资源,并且我们想提供会话信息,我们可以使用encodeRedirectURL()
方法。
阅读更多:Servlet URL Rewriting
Cookies are used a lot in web client-server communication, it’s not something specific to java. Cookies are text data sent by server to the client and it gets saved at the client local machine.
Servlet API provides cookies support through javax.servlet.http.Cookie
class that implements Serializable
and Cloneable
interfaces.
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.
Similarly HttpServletResponse
addCookie(Cookie c)
method is provided to attach cookie in response header, there are no getter methods for cookie.
Read more at Cookies in Servlets.
Cookies 在 web 客户端-服务器 通信中使用很多,这不是 Java 特有的。Cooikie 是由服务器发送给客户端并保存客户端本地机器上的文本数据。
Servlet API 通过实现Serializable
和Cloneable
接口的javax.servlet.http.Cookie
类提供了 cookies 的支持。
HttpServletRequest
的getCookies()
方法来用于从请求中获取 Cookies 数组,因为添加 Cookie 到 request 没有任何意义,所以没有方法来 set 或者 add cookie 到 request。
同样提供了HttpServletResponse
的addCookie(Cookie c)
方法来在响应头中附加 cookie,没有针对 cookie 的 getter 方法。
阅读更多: Cookies in Servlets.
If we have to make sure an object gets notified when session is destroyed, the object should implement javax.servlet.http.HttpSessionBindingListener
interface. This interface defines two callback methods – valueBound()
and valueUnbound()
that we can define to implement processing logic when the object is added as attribute to the session and when session is destroyed.
Recommended reading Servlet Listener.
如果我们必须却奥一个对象在会话销毁时得到通过,那么该对象应该实现javax.servlet.http.HttpSessionBindingListener
接口。这个接口定义了两个回调方法 - valueBound()
和valueUnbound()
我们可以定义它们来实处理逻辑,当对象作为属性添加到会话中并且会话被销毁时。
未完待续