servlet面试常问问题
Servlets is a very important topic of Java EE and all of the web applications frameworks such as Spring and Struts is built on top of it. This makes servlet interview questions a hot topic in interviews.
Servlet是Java EE的一个非常重要的主题,所有Web应用程序框架(例如Spring和Struts)都建立在它之上。 这使得servlet采访问题成为采访中的热门话题。
Here I am providing a list of 50 servlet interview questions with answers to help you tackle most of the interview questions related to servlets and web applications in java.
在这里,我提供了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 the 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 the Application server is a web server with additional functionalities to help developers with enterprise applications.
Web服务器的职责是处理来自客户端浏览器的HTTP请求并以HTML响应进行响应。 Web服务器可以理解HTTP语言并可以在HTTP协议上运行。
Apache Web Server是一种Web服务器,然后我们有可以执行servlet和JSP的特定容器,称为servlet容器,例如Tomcat。
Application Server提供了其他功能,例如Enterprise JavaBeans支持,JMS Messaging支持,事务管理等。因此,可以说Application Server是一个Web服务器,具有其他功能来帮助开发人员使用企业应用程序。
An 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 the same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.
For example, to access an HTML page or image, we should use GET because it will always return the same object but if we have to save customer information to the database, we should use the POST method. Idempotent methods are also known as safe methods and we don’t care about the repetitive request from the client for safe methods.
如果HTTP方法每次都返回相同的结果,则它被认为是幂等的。 HTTP方法GET,PUT,DELETE,HEAD和OPTIONS是幂等方法,我们应该实现我们的应用程序,以确保这些方法始终返回相同的结果。 HTTP方法POST是非幂等方法,在实现随每个请求更改的内容时,我们应该使用post方法。
例如,要访问HTML页面或图像,我们应该使用GET,因为它总是返回相同的对象,但是如果我们必须将客户信息保存到数据库中,则应该使用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 a file through servlet from the server.
“ Content-Type”响应头被称为MIME类型。 服务器将MIME类型发送给客户端,以使客户端知道其发送的数据类型。 它可以帮助客户端为用户呈现数据。 一些最常用的mime类型是text / html,text / xml,application / xml等。
我们可以使用ServletContext getMimeType()方法来获取文件的正确MIME类型,并使用它来设置响应内容类型。 在通过servlet从服务器下载文件时,这非常有用。
Web Applications are modules that run on the server to provide both static and dynamic content to the client browser. Apache webserver supports PHP and we can create a 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 the 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存档(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 that’s why we mostly extend HttpServlet class. Servlet API hierarchy is shown in the below image.
Read more at Servlet Tutorial.
Java Servlet是服务器端技术,通过提供对动态响应和数据持久性的支持来扩展Web服务器的功能。
javax.servlet
和javax.servlet.http
包提供用于编写我们自己的servlet的接口和类。
所有servlet必须实现javax.servlet.Servlet接口,该接口定义了servlet生命周期方法。 在实现通用服务时,我们可以扩展Java Servlet API随附的GenericServlet类。 HttpServlet类提供用于处理特定于HTTP的服务的方法,例如doGet()和doPost()。
大多数情况下,Web应用程序是使用HTTP协议访问的,这就是为什么我们主要扩展HttpServlet类的原因。 下图显示了Servlet API层次结构。
在Servlet教程中阅读更多内容。
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:
Servlet容器也称为Web容器,例如Tomcat。 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
用于将配置信息传递给Servlet。 每个servlet都有自己的ServletConfig对象,并且servlet容器负责实例化此对象。 我们可以在web.xml文件中或通过使用WebInitParam批注提供servlet初始化参数。 我们可以使用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
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对象,并使用
ServletSpec 3中增强了ServletContext,以引入一些方法,通过这些方法,我们可以以编程方式向应用程序添加侦听器,过滤器和Servlet。 它还提供了一些实用的方法,例如getMimeType() , getResourceAsStream()等。
Some of the differences between ServletConfig and ServletContext are:
ServletConfig和ServletContext之间的一些区别是:
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in the 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:
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。 我们还可以使用它来将另一个资源的内容包括到响应中。 此接口用于同一上下文中的servlet间通信。
此接口中定义了两种方法:
我们可以使用ServletContext的getRequestDispatcher(String path)方法在Servlet中获取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将基于字符的信息(例如,字符数组和String)写入响应,而我们可以使用ServletOutputStream将字节数组数据写入响应。
我们可以使用ServletResponse getWriter()获取PrintWriter实例,而我们可以使用ServletResponse getOutputStream()方法获取ServletOutputStream对象引用。
您可以在Java IO教程中阅读有关Java的更多信息。
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()方法和doGet()方法中的doPost()方法调用doPost()方法即可在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, that’s why this interface is Deprecated in Servlet 2.4.
提供SingleThreadModel接口是为了确保线程安全,它确保在servlet的service方法中不会同时执行两个线程。 但是,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 the 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 it’s of any use because we won’t be having access to the ServletConfig object until unless servlet is initialized by the container. Ideally, if we have to initialize any resource for the 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 the 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应用程序中设置,获取和删除属性。 servlet属性有三个范围-请求范围,会话范围和应用程序范围。
ServletRequest,HttpSession和ServletContext接口分别提供了从请求,会话和应用程序范围获取/设置/删除属性的方法。
Servlet属性与web.xml中为ServletConfig或ServletContext定义的初始化参数不同。
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输出,则可以使用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 the ServletResponse sendRedirect() method and provide the complete URL of another servlet. This sends the response to the client with the 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,以将请求转发到另一个URL。 如果还必须发送一些数据,则可以使用cookie,它将作为servlet响应的一部分,并将请求发送到另一个servlet。
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协议实现,但由于在诸如getGet()和doPost()之类的服务方法中没有实现逻辑,因此它仍然是抽象的,我们应该重写至少一个服务方法。 这就是为什么拥有HttpServlet实例并被声明为抽象类毫无意义的原因。
阅读有关抽象类的更多信息。
We know that Servlet Container manages the life cycle of Servlet, there are four phases of servlet life cycle.
我们知道Servlet容器管理Servlet的生命周期,Servlet生命周期分为四个阶段。
Servlet Life Cycle consists of three methods:
Servlet生命周期包含三种方法:
If we have to initialize some resource before we want our servlet to process client requests, we should override the 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(ServletConfig config)方法。 这就是为什么GenericServlet提供了另一个帮助程序init()方法,该方法没有在init(ServletConfig config)方法末尾调用的参数。 我们应该始终利用此方法来覆盖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 strips the white spaces and replaces 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编码是将数据转换为CGI格式的过程,以便它可以毫无问题地跨网络传输。 URL编码会去除空格,并用转义符替换特殊字符。 我们可以使用java.net.URLEncoder.encode(String str,String unicode)对String进行编码。 URL解码是编码的反向过程,我们可以使用java.net.URLDecoder.decode(String str,String unicode)对编码的字符串进行解码。 例如,“ Pankaj的数据”被编码为“ Pankaj%27s + Data”。
The session is a conversational state between client and server and it can consist 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.
会话是客户端和服务器之间的会话状态,它可以包含客户端和服务器之间的多个请求和响应。 由于HTTP和Web Server都是无状态的,因此维护会话的唯一方法是在每次请求和响应中在服务器和客户端之间传递有关会话的一些唯一信息(session-id)。
Servlet中会话管理的一些常见方法是:
在Servlet会话管理教程中详细了解有关这些会话管理方法的更多信息。
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 a 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编码的另一个好处是,它是一种后备方法,只有在禁用浏览器cookie的情况下,它才能启动。
我们可以使用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 the request, since there is no point of adding Cookie to request, there are no methods to set or add a cookie to request.
Similarly, HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in the response header, there are no getter methods for a cookie.
Read more at Cookies in Servlets.
Cookie在Web客户端与服务器之间的通信中被大量使用,它不是Java特有的。 Cookies是服务器发送到客户端的文本数据,并保存在客户端本地计算机上。
Servlet API通过实现Serializable和Cloneable接口的javax.servlet.http.Cookie类提供cookie支持。
提供HttpServletRequest getCookies()方法可从请求中获取Cookie数组,因为没有向请求添加Cookie的意义,所以没有设置或向请求添加Cookie的方法。
同样,提供了HttpServletResponse addCookie(Cookie c)方法来将cookie附加到响应标头中,没有用于cookie的getter方法。
在Servlet中的Cookies中了解更多信息。
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(),当将对象作为属性添加到会话中以及销毁会话时,我们可以定义它们以实现处理逻辑。
建议阅读Servlet Listener 。
HttpServletResponse provide method to encode URL in HTML hyperlinks so that the special characters and white spaces are escaped and append session id to the URL. It behaves similar to URLEncoder encode method with additional process to append jsessionid parameter at the end of the URL.
However HttpServletResponse encodeRedirectUrl() method is used specially for encode the redirect URL in response.
So when we are providing URL rewriting support, for hyperlinks in HTML response, we should use encodeURL() method whereas for redirect URL we should use encodeRedirectUrl() method.
HttpServletResponse提供了在HTML超链接中对URL进行编码的方法,以便转义特殊字符和空格并将会话ID附加到URL。 它的行为类似于URLEncoder编码方法,但具有额外的过程以在URL末尾附加jsessionid参数。
但是,HttpServletResponse encodeRedirectUrl()方法专门用于对响应中的重定向URL进行编码。
因此,当我们提供URL重写支持时,对于HTML响应中的超链接,我们应该使用encodeURL()方法,而对于重定向URL,我们应该使用encodeRedirectUrl()方法。
Servlet Filters are pluggable java components that we can use to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.
Some common tasks that we can do with filters are:
Read more about filters at Servlet Filter.
Servlet过滤器是可插入的Java组件,我们可以使用它们来拦截和处理请求,然后再将请求发送到servlet,并在servlet代码完成之后以及容器将响应发送回客户端之前进行响应。
我们可以使用过滤器执行的一些常见任务是:
在Servlet Filter中阅读有关过滤器的更多信息。
We know that servlet filters can be used to intercept request between a servlet container and servlet, we can utilize it to create an authentication filter and check if the request contains a valid session or not.
Check out Authentication Filter example at Servlet Filter Example.
我们知道servlet过滤器可用于拦截servlet容器和servlet之间的请求,我们可以利用它来创建身份验证过滤器,并检查请求是否包含有效会话。
在Servlet筛选器示例中查看Authentication Filter的示例。
We know that using ServletContext, we can create an attribute with application scope that all other servlets can access but we can initialize ServletContext init parameters as String only in the deployment descriptor (web.xml). What if our application is database-oriented and we want to set an attribute in ServletContext for Database Connection.
If your application has a single entry point (user login), then you can do it in the first servlet request but if we have multiple entry points then doing it everywhere will result in a lot of code redundancy. Also if the database is down or not configured properly, we won’t know until the first client request comes to the server. To handle these scenarios, servlet API provides Listener interfaces that we can implement and configure to listen to an event and do certain operations.
Read more about different types of listeners and example at Servlet Listener.
我们知道,使用ServletContext,我们可以创建一个应用程序范围内的属性,所有其他servlet都可以访问该属性,但是我们只能在部署描述符(web.xml)中将ServletContext初始化参数初始化为String。 如果我们的应用程序是面向数据库的,并且我们想在ServletContext中为数据库连接设置一个属性,该怎么办?
如果您的应用程序只有一个入口点(用户登录),那么您可以在第一个servlet请求中进行操作,但是如果我们有多个入口点,那么在任何地方进行操作都会导致大量代码冗余。 此外,如果数据库已关闭或配置不正确,我们将在第一个客户端请求到达服务器之前才知道。 为了处理这些情况,Servlet API提供了侦听器接口,我们可以将其实现和配置为侦听事件并执行某些操作。
在Servlet Listener上了解有关不同类型的侦听器和示例的更多信息。
If you notice, doGet() and doPost() methods throw ServletException and IOException. Since browser understand only HTML, when our application throw exception, servlet container processes the exception and generate a HTML response. Same goes with other error codes like 404, 403 etc.
Servlet API provides support for custom Exception and Error Handler servlets that we can configure in the deployment descriptor, the whole purpose of these servlets are to handle the Exception or Error raised by application and send HTML response that is useful for the user. We can provide a link to the application home page or some details to let the user know what went wrong.
We can configure them in web.xml like below:
404
/AppExceptionHandler
javax.servlet.ServletException
/AppExceptionHandler
Read more at Servlet Exception Handling.
如果您注意到,doGet()和doPost()方法将抛出ServletException和IOException。 由于浏览器仅了解HTML,因此当我们的应用程序引发异常时,servlet容器将处理该异常并生成HTML响应。 其他错误代码(例如404、403等)也是如此。
Servlet API支持可在部署描述符中配置的自定义Exception和Error Handler Servlet,这些Servlet的全部目的是处理应用程序引发的Exception或Error并发送对用户有用HTML响应。 我们可以提供到应用程序主页的链接或一些详细信息,以使用户知道出了什么问题。
我们可以在web.xml中配置它们,如下所示:
在Servlet异常处理中阅读更多内容。
The deployment descriptor is a configuration file for the web application and its name is web.xml and it resides in WEB-INF directory. Servlet container uses this file to configure web application servlets, servlet config params, context init params, filters, listeners, welcome pages and error handlers.
With servlet 3.0 annotations, we can remove a lot of clutter from web.xml by configuring servlets, filters, and listeners using annotations.
部署描述符是Web应用程序的配置文件,名称是web.xml,它位于WEB-INF目录中。 Servlet容器使用此文件来配置Web应用程序Servlet,Servlet配置参数,上下文初始化参数,过滤器,侦听器,欢迎页面和错误处理程序。
使用Servlet 3.0批注,通过使用批注配置Servlet,过滤器和侦听器,我们可以从web.xml中消除很多混乱。
Usually, servlet container loads a servlet on the first client request. Sometimes the servlet is heavy and takes time to loads, we might want to load it on application startup. We can use a load-on-startup element with servlet configuration in the web.xml file or use WebServlet annotation loadOnStartup variable to tell the container to load the servlet on system startup.
foo
com.foo.servlets.Foo
5
The load-on-startup value should be int, if it’s a negative integer then servlet container will load the servlet based on client requests and requirement but if it’s 0 or positive, then the container will load it on application startup.
If there are multiple servlets with load-on-startup value such as 0,1,2,3 then lower integer value servlet will be loaded first.
通常,servlet容器在第一个客户端请求上加载servlet。 有时servlet很重并且需要花费一些时间来加载,我们可能希望在应用程序启动时加载它。 我们可以在web.xml文件中使用带有servlet配置的load-on-startup元素,或者使用WebServlet注释loadOnStartup变量来告诉容器在系统启动时加载servlet。
启动时加载的值应为int,如果它是负整数,则servlet容器将根据客户端请求和要求加载servlet,但如果它是0或正数,则容器将在应用程序启动时加载它。
如果有多个servlet的启动时加载值为0、1、2、3,则将首先加载较低的整数值servlet。
We can use following code snippet to get the actual path of the servlet in file system.
getServletContext().getRealPath(request.getServletPath())
我们可以使用以下代码片段获取文件系统中servlet的实际路径。
getServletContext().getRealPath(request.getServletPath())
We can use below code snippet to get the servlet information in a servlet through servlet context object.
getServletContext().getServerInfo()
我们可以使用下面的代码片段通过servlet上下文对象获取servlet中的servlet信息。
getServletContext().getServerInfo()
File Upload and Download and common tasks in a java web application. Unfortunately Servlet API doesn’t provide easy methods to upload file on server, so we can use Apache FileUpload jar to make our life easier.
Please read File Upload Servlet post that provide all the necessary details with example program to upload and download file using servlets.
Java Web应用程序中的文件上载和下载以及常见任务。 不幸的是,Servlet API没有提供在服务器上上传文件的简便方法,因此我们可以使用Apache FileUpload jar来简化我们的生活。
请阅读“ 文件上传Servlet”一文 ,其中提供了所有必要的详细信息以及示例程序,以使用Servlet上传和下载文件。
If you work with database connection a lot in your web application, its best to initialize it in a servlet context listener and set it as a context attribute for other servlets to use.
Integrating Log4j is also very easy in web applications, all we need is a log4j configuration XML or property file and then configure it in a servlet context listener.
For complete example, please look into Servlet Database and Log4j Example.
如果您在Web应用程序中经常使用数据库连接,则最好在Servlet上下文侦听器中对其进行初始化,并将其设置为其他Servlet使用的上下文属性。
在Web应用程序中,集成Log4j也非常容易,我们需要的是一个log4j配置XML或属性文件,然后在servlet上下文侦听器中对其进行配置。
有关完整的示例,请查看Servlet数据库和Log4j示例 。
We can use request.getRemoteAddr()
to get the client IP address in servlet.
我们可以使用request.getRemoteAddr()
获取Servlet中的客户端IP地址。
Servlet Specs 3.0 was a major release and some of the important features are:
Servlet 3 introduced the use of Java annotations to define a servlet, filter and listener servlets and init parameters. Some of the important Servlet API annotations are WebServlet, WebInitParam, WebFilter, and WebListener. Read more about them at Servlet 3 annotations.
Servlet Specs 3.0是一个主要版本,其中一些重要功能包括:
Servlet 3引入了使用Java批注来定义servlet,过滤器和侦听器servlet以及init参数的方法。 一些重要的Servlet API批注是WebServlet,WebInitParam,WebFilter和WebListener。 在Servlet 3注释中阅读有关它们的更多信息。
Servlet Container provides different ways of login based servlet authentication:
Servlet Container provides different ways of login based servlet authentication:
We can configure our servlet container to use SSL for message communication over the network. To configure SSL on Tomcat, we need a digital certificate that can be created using Java keytool for a development environment. For the production environment, you should get the digital certificate from SSL certificate providers, for example, Verisign or Entrust.
Read more at Configure SSL on Tomcat article.
We can configure our servlet container to use SSL for message communication over the network. To configure SSL on Tomcat, we need a digital certificate that can be created using Java keytool for a development environment. For the production environment, you should get the digital certificate from SSL certificate providers, for example, Verisign or Entrust.
Read more at Configure SSL on Tomcat article.
That’s all for the servlet interview questions and answers. I will keep on adding more servlet based interview questions to the list in the future, so don’t forget to bookmark it for future reference.
That's all for the servlet interview questions and answers. I will keep on adding more servlet based interview questions to the list in the future, so don't forget to bookmark it for future reference.
Please share your thoughts in comments and share your love with sharing on Google Plus, Facebook or Twitter.
Please share your thoughts in comments and share your love with sharing on Google Plus, Facebook or Twitter.
Update: If you liked these questions, I am sure you will like JSP Interview Questions too.
Update : If you liked these questions, I am sure you will like JSP Interview Questions too.
References:
参考文献:
翻译自: https://www.journaldev.com/2015/servlet-interview-questions-and-answers
servlet面试常问问题