servlet面试常问问题_50个Servlet面试问答

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应用程序有关的大多数面试问题。

Servlet面试问题 (Servlet Interview Questions)

  1. What is different between web server and application server?

    Web服务器和应用程序服务器之间有什么区别?
  2. Which HTTP method is non-idempotent?

    哪种HTTP方法不是幂等的?
  3. What is the difference between GET and POST method?

    GET和POST方法有什么区别?
  4. What is MIME Type?

    什么是MIME类型?
  5. What is a web application and what is its directory structure?

    什么是Web应用程序,其目录结构是什么?
  6. What is a servlet?

    什么是servlet?
  7. What are the advantages of Servlet over CGI?

    Servlet比CGI有什么优势?
  8. What are common tasks performed by Servlet Container?

    Servlet容器执行哪些常见任务?
  9. What is ServletConfig object?

    什么是ServletConfig对象?
  10. What is ServletContext object?

    什么是ServletContext对象?
  11. What is difference between ServletConfig and ServletContext?

    ServletConfig和ServletContext有什么区别?
  12. What is Request Dispatcher?

    什么是请求分派器?
  13. What is difference between PrintWriter and ServletOutputStream?

    PrintWriter和ServletOutputStream有什么区别?
  14. Can we get PrintWriter and ServletOutputStream both in a servlet?

    我们可以同时在Servlet中获得PrintWriter和ServletOutputStream吗?
  15. How can we create deadlock situation in servlet?

    我们如何在servlet中创建死锁情况?
  16. What is the use of servlet wrapper classes?

    servlet包装器类有什么用?
  17. What is SingleThreadModel interface?

    什么是SingleThreadModel接口?
  18. Do we need to override service() method?

    我们需要重写service()方法吗?
  19. Is it good idea to create servlet constructor?

    创建servlet构造函数是个好主意吗?
  20. What is difference between GenericServlet and HttpServlet?

    GenericServlet和HttpServlet有什么区别?
  21. What is the inter-servlet communication?

    servlet间的通信是什么?
  22. Are Servlets Thread Safe? How to achieve thread safety in servlets?

    Servlet线程安全吗? 如何在servlet中实现线程安全?
  23. What is servlet attributes and their scope?

    什么是servlet属性及其范围?
  24. How do we call one servlet from another servlet?

    我们如何从另一个servlet调用一个servlet?
  25. How can we invoke another servlet in a different application?

    我们如何在不同的应用程序中调用另一个servlet?
  26. What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?

    ServletResponse sendRedirect()和RequestDispatcher forward()方法之间有什么区别?
  27. Why HttpServlet class is declared abstract?

    为什么HttpServlet类被声明为抽象的?
  28. What are the phases of servlet life cycle?

    Servlet生命周期的哪些阶段?
  29. What are life cycle methods of a servlet?

    Servlet的生命周期方法是什么?
  30. why we should override only no-agrs init() method.

    为什么我们应该只覆盖no-agrs init()方法。
  31. What is URL Encoding?

    什么是网址编码?
  32. What are different methods of session management in servlets?

    Servlet中的会话管理有哪些不同的方法?
  33. What is URL Rewriting?

    什么是URL重写?
  34. How does Cookies work in Servlets?

    Cookies如何在Servlet中工作?
  35. How to notify an object in session when session is invalidated or timed-out?

    当会话无效或超时时,如何在会话中通知对象?
  36. What is the difference between encodeRedirectUrl and encodeURL?

    encodeRedirectUrl和encodeURL有什么区别?
  37. Why do we have servlet filters?

    为什么我们有servlet过滤器?
  38. What is the effective way to make sure all the servlets are accessible only when user has a valid session?

    确保仅当用户具有有效会话时才可访问所有servlet的有效方法是什么?
  39. Why do we have servlet listeners?

    为什么我们有servlet侦听器?
  40. How to handle exceptions thrown by application with another servlet?

    如何处理应用程序使用另一个Servlet引发的异常?
  41. What is a deployment descriptor?

    什么是部署描述符?
  42. How to make sure a servlet is loaded at the application startup?

    如何确保在应用程序启动时加载了servlet?
  43. How to get the actual path of servlet in server?

    如何获取服务器中servlet的实际路径?
  44. How to get the server information in a servlet?

    如何在servlet中获取服务器信息?
  45. Write a servlet to upload file on server.

    编写一个Servlet以在服务器上上传文件。
  46. How do we go with database connection and log4j integration in servlet?

    我们如何进行servlet中的数据库连接和log4j集成?
  47. How to get the IP address of client in servlet?

    如何在servlet中获取客户端的IP地址?
  48. What are important features of Servlet 3?

    Servlet 3的重要功能是什么?
  49. What are different ways for servlet authentication?

    servlet身份验证有哪些不同的方法?
  50. How can we achieve transport layer security for our web application?

    我们如何为我们的Web应用程序实现传输层安全性?

Servlet面试问答 (Servlet Interview Questions and Answers)

  1. Web服务器和应用程序服务器之间有什么区别? (What is different between web server and application server?)

    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服务器,具有其他功能来帮助开发人员使用企业应用程序。

  2. 哪种HTTP方法不是幂等的? (Which HTTP method is non-idempotent?)

    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方法。 幂等方法也称为安全方法,我们不在乎客户端对安全方法的重复请求。

  3. GET和POST方法有什么区别? (What is the difference between GET and POST method?)

    • GET is a safe method (idempotent) where POST is non-idempotent method.
    • We can send limited data with GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.
    • GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can’t bookmark it.
    • GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.
    • Hyperlinks in a page uses GET method.

    • GET是一种安全方法(幂等),其中POST是非幂等方法。
    • 我们可以使用GET方法发送有限的数据,并将其发送到标头请求URL中,而我们可以使用POST发送大量数据,因为它是正文的一部分。
    • GET方法是不安全的,因为数据在URL中公开,我们可以轻松为其添加书签并再次发送类似的请求,而POST是安全的,因为数据是在请求正文中发送的,因此我们无法对其添加书签。
    • GET是默认的HTTP方法,而我们需要将方法指定为POST才能使用POST方法发送请求。
    • 页面中的超链接使用GET方法。
  4. 什么是MIME类型? (What is MIME Type?)

    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从服务器下载文件时,这非常有用。

  5. 什么是Web应用程序,其目录结构是什么? (What is a web application and what is its directory structure?)

    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应用程序的更多信息。

  6. 什么是servlet? (What is a servlet?)

    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.servletjavax.servlet.http包提供用于编写​​我们自己的servlet的接口和类。

    所有servlet必须实现javax.servlet.Servlet接口,该接口定义了servlet生命周期方法。 在实现通用服务时,我们可以扩展Java Servlet API随附的GenericServlet类。 HttpServlet类提供用于处理特定于HTTP的服务的方法,例如doGet()和doPost()。

    大多数情况下,Web应用程序是使用HTTP协议访问的,这就是为什么我们主要扩展HttpServlet类的原因。 下图显示了Servlet API层次结构。

    Servlet教程中阅读更多内容。

  7. Servlet比CGI有什么优势? (What are the advantages of Servlet over CGI?)

    Servlet technology was introduced to overcome the shortcomings of CGI technology.

    • Servlets provide better performance than CGI in terms of processing time, memory utilization because servlets use benefits of multithreading and for each request, a new thread is created, that is faster than loading creating new Object for each request with CGI.
    • Servlets and platform and system independent, the web application developed with Servlet can be run on any standard web container such as Tomcat, JBoss, Glassfish servers and on operating systems such as Windows, Linux, Unix, Solaris, Mac, etc.
    • Servlets are robust because container takes care of the life cycle of servlet and we don’t need to worry about memory leaks, security, garbage collection, etc.
    • Servlets are maintainable and the learning curve is small because all we need to take care is business logic for our application.

    引入Servlet技术是为了克服CGI技术的缺点。

    • Servlet在处理时间,内存利用率方面比CGI更好,因为Servlet利用了多线程的优势,并且为每个请求创建了一个新线程,比为CGI为每个请求加载创建新对象要快。
    • 用Servlet开发的Web应用程序与Servlet和平台和系统无关,可以在任何标准Web容器上运行,例如Tomcat,JBoss,Glassfish服务器以及在Windows,Linux,Unix,Solaris,Mac等操作系统上运行。
    • Servlet非常健壮,因为容器负责Servlet的生命周期,因此我们不必担心内存泄漏,安全性,垃圾回收等问题。
    • Servlet是可维护的,学习曲线很小,因为我们需要注意的是应用程序的业务逻辑。
  8. Servlet容器执行哪些常见任务? (What are common tasks performed by Servlet Container?)

    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 the container, we don’t need to build a server socket to listen for any request from the web client, parse the request and generate a 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. The container also provides utility like JNDI for resource pooling and management.
    • Multithreading Support: Container creates a new thread for every request to the servlet and provides them request and response objects to the processing. So servlets are not initialized for each request and save 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容器的一些重要任务是:

    • 通讯支持 :Servlet容器提供了Web客户端(浏览器)与Servlet和JSP之间的简便通讯方式。 由于有了容器,我们不需要构建服务器套接字来侦听来自Web客户端的任何请求,解析请求并生成响应。 所有这些重要而复杂的任务都是由容器完成的,我们需要关注的只是应用程序的业务逻辑。
    • 生命周期和资源管理 :Servlet容器负责管理 Servlet的生命周期。 从将servlet加载到内存中,初始化servlet,调用servlet方法并销毁它们。 该容器还提供实用程序(如JNDI)来进行资源池和管理。
    • 多线程支持 :容器为对Servlet的每个请求创建一个新线程,并为它们提供处理的请求和响应对象。 因此,不必为每个请求初始化servlet,这样可以节省时间和内存。
    • JSP支持 :JSP看起来不像普通的Java类,但是应用程序中的每个JSP都由容器编译并转换为Servlet,然后容器像其他Servlet一样管理它们。
    • 杂项任务 :Servlet容器管理资源池,执行内存优化,执行垃圾收集器,提供安全配置,支持多个应用程序,热部署以及其他一些后台任务,这些任务使开发人员的工作变得更轻松。
  9. 什么是ServletConfig对象? (What is ServletConfig object?)

    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对象。

  10. 什么是ServletContext对象? (What is ServletContext object?)

    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容器还可以提供一组Servlet唯一的上下文对象,并且该上下文对象与主机的URL路径名称空间的特定部分相关联。

    ServletSpec 3中增强了ServletContext,以引入一些方法,通过这些方法,我们可以以编程方式向应用程序添加侦听器,过滤器和Servlet。 它还提供了一些实用的方法,例如getMimeType()getResourceAsStream()等。

  11. ServletConfig和ServletContext有什么区别? (What is difference between ServletConfig and ServletContext?)

    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.
    • We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.

    ServletConfig和ServletContext之间的一些区别是:

    • ServletConfig是每个Servlet的唯一对象,而ServletContext是完整应用程序的唯一对象。
    • ServletConfig用于向Servlet提供初始化参数,而ServletContext用于提供所有其他Servlet可以使用的应用程序级初始化参数。
    • 我们不能在ServletConfig对象中设置属性,而可以在ServletContext中设置其他servlet可以在其​​实现中使用的属性。
  12. 什么是请求分派器? (What is Request Dispatcher?)

    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:

    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。 我们还可以使用它来将另一个资源的内容包括到响应中。 此接口用于同一上下文中的servlet间通信。

    此接口中定义了两种方法:

    1. void forward(ServletRequest请求,ServletResponse响应)–将请求从Servlet转发到服务器上的另一个资源(Servlet,JSP文件或HTML文件)。
    2. void include(ServletRequest request,ServletResponse response)–在响应中包含资源的内容(Servlet,JSP页面,HTML文件)。
    3. 我们可以使用ServletContext的getRequestDispatcher(String path)方法在Servlet中获取RequestDispatcher。 该路径必须以/开头,并被解释为相对于当前上下文根。

  13. PrintWriter和ServletOutputStream有什么区别? (What is difference between PrintWriter and ServletOutputStream?)

    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的更多信息。

  14. 我们可以同时在Servlet中获得PrintWriter和ServletOutputStream吗? (Can we get PrintWriter and ServletOutputStream both in a servlet?)

    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 ,因为已经为此响应调用了其他方法。

  15. 我们如何在servlet中创建死锁情况? (How can we create deadlock situation in servlet?)

    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中阅读有关多线程中死锁的更多信息。

  16. servlet包装器类有什么用? (What is the use of servlet wrapper classes?)

    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提供了两个包装器类– HttpServletRequestWrapperHttpServletResponseWrapper 。 提供这些包装器类可帮助开发人员自定义实现Servlet请求和响应类型。 我们可以扩展这些类,并仅覆盖为自定义请求和响应对象需要实现的特定方法。 在普通的servlet编程中不使用这些类。

  17. 什么是SingleThreadModel接口? (What is SingleThreadModel interface?)

    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中不推荐使用此接口的原因。

  18. 我们需要重写service()方法吗? (Do we need to override service() method?)

    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过滤器和侦听器。

  19. 创建servlet构造函数是个好主意吗? (Is it good idea to create servlet constructor?)

    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的初始化参数。

  20. GenericServlet和HttpServlet有什么区别? (What is difference between GenericServlet and HttpServlet?)

    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协议的方法。

  21. servlet间的通信是什么? (What is the inter-servlet communication?)

    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使用。

  22. Servlet线程安全吗? 如何在servlet中实现线程安全? (Are Servlets Thread Safe? How to achieve thread-safety in servlets?)

    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中阅读有关它们的更多信息。

  23. 什么是servlet属性及其范围? (What is servlet attributes and their scope?)

    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定义的初始化参数不同。

  24. 我们如何从另一个servlet调用一个servlet? (How do we call one servlet from another servlet?)

    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()方法。

  25. 我们如何在不同的应用程序中调用另一个servlet? (How can we invoke another servlet in a different application?)

    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。

  26. ServletResponse sendRedirect()和RequestDispatcher forward()方法之间有什么区别? (What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?)

    1. 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.
    2. forward() is handled internally by the container whereas sednRedirect() is handled by browser.
    3. We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.
    4. In 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.
    5. forward() can’t be used to invoke a servlet in another context, we can only use sendRedirect() in this case.

    1. RequestDispatcher forward()用于将同一请求转发到另一个资源,而ServletResponse sendRedirect()是一个两步过程。 在sendRedirect()中,Web应用程序使用状态码302(重定向)和URL将响应返回给客户端,以发送请求。 发送的请求是一个全新的请求。
    2. forward()由容器内部处理,而sednRedirect()由浏览器处理。
    3. 访问同一应用程序中的资源时,我们应该使用forward(),因为它比需要额外网络调用的sendRedirect()方法要快。
    4. 在forward()中,浏览器不了解实际的处理资源,并且地址栏中的URL保持不变,而在sendRedirect()中,地址栏中的URL更改为转发的资源。
    5. forward()不能用于在另一个上下文中调用servlet,在这种情况下,我们只能使用sendRedirect()。
  27. 为什么HttpServlet类被声明为抽象的? (Why HttpServlet class is declared abstract?)

    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实例并被声明为抽象类毫无意义的原因。

    阅读有关抽象类的更多信息。

  28. Servlet生命周期的哪些阶段? (What are the phases of servlet life cycle?)

    We know that Servlet Container manages the life cycle of Servlet, there are four phases of servlet life cycle.

    1. Servlet Class Loading – When container receives a request for a servlet, it first loads the class into memory and calls it’s default no-args constructor.
    2. Servlet Class Initialization – Once the servlet class is loaded, container initializes the ServletContext object for the servlet and then invoke its init method by passing the servlet config object. This is the place where a servlet class transforms from normal class to servlet.
    3. Request Handling – Once the servlet is initialized, it’s ready to handle the client requests. For every client request, servlet container spawns a new thread and invokes the service() method by passing the request and response object reference.
    4. Removal from Service – When container stops or we stop the application, servlet container destroys the servlet class by invoking the destroy() method.

    我们知道Servlet容器管理Servlet的生命周期,Servlet生命周期分为四个阶段。

    1. Servlet类加载–当容器收到对Servlet的请求时,它将首先将该类加载到内存中,并调用其默认的no-args构造函数。
    2. Servlet类初始化–加载Servlet类后,容器将为Servlet初始化ServletContext对象,然后通过传递servlet配置对象来调用其init方法。 这是servlet类从普通类转换为servlet的地方。
    3. 请求处理–初始化Servlet之后,就可以处理客户端请求了。 对于每个客户端请求,servlet容器都会生成一个新线程,并通过传递请求和响应对象引用来调用service()方法。
    4. 从服务中删除–当容器停止或我们停止应用程序时,servlet容器通过调用destroy()方法破坏servlet类。
  29. Servlet的生命周期方法是什么? (What are life cycle methods of a servlet?)

    Servlet Life Cycle consists of three methods:

    1. 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.
    2. 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.
    3. public void destroy() – This method is invoked once when servlet is unloaded from memory.

    Servlet生命周期包含三种方法:

    1. public void init(ServletConfig config)–容器使用此方法初始化servlet,此方法在servlet的生命周期中仅被调用一次。
    2. 公共无效服务(ServletRequest请求,ServletResponse响应)–每个请求都调用一次此方法,除非执行init()方法,否则容器无法调用service()方法。
    3. public void destroy()–当从内存中卸载servlet时,将调用此方法一次。
  30. 为什么我们应该只覆盖no-agrs init()方法。 (why we should override only no-agrs init() method.)

    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()调用。

  31. 什么是网址编码? (What is URL Encoding?)

    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”。

  32. Servlet中的会话管理有哪些不同的方法? (What are different methods of session management in servlets?)

    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:

    1. User Authentication
    2. HTML Hidden Field
    3. Cookies
    4. URL Rewriting
    5. Session Management API

    Read more about these session management approaches in detail at Servlet Session Management Tutorial.

    会话是客户端和服务器之间的会话状态,它可以包含客户端和服务器之间的多个请求和响应。 由于HTTP和Web Server都是无状态的,因此维护会话的唯一方法是在每次请求和响应中在服务器和客户端之间传递有关会话的一些唯一信息(session-id)。

    Servlet中会话管理的一些常见方法是:

    1. 用户认证
    2. HTML隐藏字段
    3. 饼干
    4. URL重写
    5. 会话管理API

    Servlet会话管理教程中详细了解有关这些会话管理方法的更多信息。

  33. 什么是URL重写? (What is URL Rewriting?)

    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上阅读更多内容。

  34. Cookies如何在Servlet中工作? (How does Cookies work in Servlets?)

    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中了解更多信息。

  35. 当会话无效或超时时,如何在会话中通知对象? (How to notify an object in session when session is invalidated or timed-out?)

    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

  36. encodeRedirectUrl和encodeURL有什么区别? (What is the difference between encodeRedirectUrl and encodeURL?)

    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()方法。

  37. 为什么我们有servlet过滤器? (Why do we have servlet filters?)

    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:

    • Logging request parameters to log files.
    • Authentication and authorization of request for resources.
    • Formatting of request body or header before sending it to servlet.
    • Compressing the response data sent to the client.
    • Alter response by adding some cookies, header information etc.

    Read more about filters at Servlet Filter.

    Servlet过滤器是可插入的Java组件,我们可以使用它们来拦截和处理请求,然后再将请求发送到servlet,并在servlet代码完成之后以及容器将响应发送回客户端之前进行响应。

    我们可以使用过滤器执行的一些常见任务是:

    • 记录请求参数以记录文件。
    • 资源请求的认证和授权。
    • 在将请求正文或标头发送到servlet之前进行格式化。
    • 压缩发送给客户端的响应数据。
    • 通过添加一些cookie,标头信息等来更改响应。

    Servlet Filter中阅读有关过滤器的更多信息。

  38. 确保仅当用户具有有效会话时才可访问所有servlet的有效方法是什么? (What is the effective way to make sure all the servlets are accessible only when the user has a valid session?)

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

  39. 为什么我们有servlet侦听器? (Why do we have servlet listeners?)

    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上了解有关不同类型的侦听器和示例的更多信息。

  40. 如何处理应用程序使用另一个Servlet引发的异常? (How to handle exceptions thrown by application with another servlet?)

    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异常处理中阅读更多内容。

  41. 什么是部署描述符? (What is a deployment descriptor?)

    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中消除很多混乱。

  42. 如何确保在应用程序启动时加载了servlet? (How to make sure a servlet is loaded at the application startup?)

    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。

  43. 如何获取服务器中servlet的实际路径? (How to get the actual path of servlet in server?)

    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())

  44. 如何在servlet中获取服务器信息? (How to get the server information in a servlet?)

    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()

  45. 编写一个Servlet以在服务器上上传文件。 (Write a servlet to upload file on server.)

    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上传和下载文件。

  46. 我们如何进行servlet中的数据库连接和log4j集成? (How do we go with database connection and log4j integration in 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示例

  47. 如何在servlet中获取客户端的IP地址? (How to get the IP address of client in servlet?)

    We can use request.getRemoteAddr() to get the client IP address in servlet.

    我们可以使用request.getRemoteAddr()获取Servlet中的客户端IP地址。

  48. Servlet 3的重要功能是什么? (What are important features of Servlet 3?)

    Servlet Specs 3.0 was a major release and some of the important features are:

    1. Servlet Annotations: Prior to Servlet 3, all the servlet mapping and its init parameters were used to defined in web.xml, this was not convenient and more error prone when number of servlets are huge in an application.

      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.

    2. Web Fragments: Prior to servlet specs 3.0, all the web application configurations are required to be present in the web.xml that makes it cluttered with a lot of elements and chances of error increases. So servlet 3 specs introduced web fragments where we can have multiple modules in a single web application, all these modules should have a web-fragment.xml file in META-INF directory. We can include all the elements of web.xml inside the web-fragment.xml too. This helps us in dividing our web application into separate modules that are included as a JAR file in the web application lib directory.
    3. Adding Web Components dynamically: We can use ServletContext object to add servlets, filters and listeners programmatically. This helps us in building a dynamic system where we are loading a component only if we need it. These methods are addServlet(), addFilter() and addListener() defined in the servlet context object.
    4. Asynchronous Processing: Asynchronous support was added to delegate the request processing to another thread rather than keeping the servlet thread busy. It can increase the throughput performance of the application. This is an advance topic and I recommend to read Async Servlet tutorial.

    Servlet Specs 3.0是一个主要版本,其中一些重要功能包括:

    1. Servlet注释 :在Servlet 3之前,所有servlet映射及其init参数都已在web.xml中定义,当应用程序中的servlet数量很大时,这样做不方便且更容易出错。

      Servlet 3引入了使用Java批注来定义servlet,过滤器和侦听器servlet以及init参数的方法。 一些重要的Servlet API批注是WebServlet,WebInitParam,WebFilter和WebListener。 在Servlet 3注释中阅读有关它们的更多信息。

    2. Web片段 :在servlet specs 3.0之前,所有Web应用程序配置都必须存在于web.xml中,这使它充满了许多元素,并且出错的机会增加了。 因此,Servlet 3规范引入了Web片段,其中我们可以在单个Web应用程序中拥有多个模块,所有这些模块都应在META-INF目录中具有一个web-fragment.xml文件。 We can include all the elements of web.xml inside the web-fragment.xml too. This helps us in dividing our web application into separate modules that are included as a JAR file in the web application lib directory.
    3. Adding Web Components dynamically : We can use ServletContext object to add servlets, filters and listeners programmatically. This helps us in building a dynamic system where we are loading a component only if we need it. These methods are addServlet(), addFilter() and addListener() defined in the servlet context object.
    4. Asynchronous Processing : Asynchronous support was added to delegate the request processing to another thread rather than keeping the servlet thread busy. It can increase the throughput performance of the application. This is an advance topic and I recommend to read Async Servlet tutorial.
  49. What are different ways for servlet authentication? (What are different ways for servlet authentication?)

    Servlet Container provides different ways of login based servlet authentication:

    1. HTTP Basic Authentication
    2. HTTP Digest Authentication
    3. HTTPS Authentication
    4. Form Based Login: A standard HTML form for authentication, advantage is that we can change the login page layout as our application requirements rather than using HTTP built-in login mechanisms.

    Servlet Container provides different ways of login based servlet authentication:

    1. HTTP Basic Authentication
    2. HTTP Digest Authentication
    3. HTTPS Authentication
    4. Form Based Login : A standard HTML form for authentication, advantage is that we can change the login page layout as our application requirements rather than using HTTP built-in login mechanisms.
  50. How can we achieve transport layer security for our web application? (How can we achieve transport layer security for our web application?)

    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://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html

    https://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html
  • https://en.wikipedia.org/wiki/Java_servlet

    https://en.wikipedia.org/wiki/Java_servlet

翻译自: https://www.journaldev.com/2015/servlet-interview-questions-and-answers

servlet面试常问问题

你可能感兴趣的:(servlet面试常问问题_50个Servlet面试问答)