Java Servlet Interview Questions and Answers

This article provide a list of java servlet interview questions and answers to help you pass the java developer or tester interview. Because servlet is the key component of java web application, it is more popular these days. There are a lot of framework such as Struts and Spring are all developed based on servlet. So this questions and answers maybe helpful for you when you are asked about Struts or Spring questions also.

1. Difference between web server, web container and application server?
  1. Web Server is used to accept HTTP request from web browser and give HTTP response back to the client. It generally serve static web resources such as html files, static images.
  2. Web Container is one step further. We can deploy and run dynamic web resources such as servlet, jsp, filter and listener in it. But it can also serve static web resources.
  3. Application Server is more powerful than web server and web container, it support all Java EE features such as EJB, JMS, JDBC, Java Transaction etc. It is used to support enterprise application.
  4. There is an article Java JEE Web Container, Application Server and Web Server Overview which can give you more introduction about the difference between them.
2. Describe java web application and it’s structure.

Java web application is a packaged war file which can run in web container for example Tomcat, Jetty etc. The main component in it is servlet and jsp. It can also include html, images, css and javascript files. Below picture is a standard file structure for a java web application.
j2ee web application file structure
Besides java web application archive, there has also java enterprise application archive. You can read Java EE Application Introduction to learn more about them.

3. Difference between HTTP Post and Get method?
  1. HTTP Post is not the default method, you need to declare it specifically when you want to post data. HTTP Get is default method, if you do not specify a method then use Get method by default.
  2. HTTP Post method is used to upload form data to web server while HTTP Get method is used to retrieve data from web server.
  3. Post method can send huge amount of data within form body, but Get method can only send limited data as header request url. The general maximize send data size for Get method is 8KB.
  4. Post method is secure because the send data is stored in the form body, we can not bookmark it. But Get method send data in the request url, so it is not secure becuause we can bookmark it and resend it again.
  5. Url links use Get method by default.
  6. Article HTTP Overview introduce all HTTP methods in detail, you can read it.
4. Explain MIME type?
  1. MIME type is the data content type which will be sent back from server to client browser. Web server save MIME type value in “Content-type” response header to tell client browser which kind of content will be rendered. The value can be text/html, text/plain, text/xml, application/pdf, img/gif etc.
  2. ServletContext’s getMimeType(java.lang.String file) method can be used to get correct MIME type for a given file. You can set the value in the response header “Content-type”, this is especially useful for download a file in servlet.
5. What is java Servlet?
  1. Java Servlet is a web component which runs in servlet container. It can produce dynamic web content.
  2. All Servlet class should implement interface javax.servlet.Servlet. The interface defines it’s life cycle method that is init(), destroy(), service().
  3. There are two pre-implemented servlet classes. You can just extend them to create your servlet class.One is GenericServlet class which is used for any protocol call. The other is HttpServlet class which is used for HTTP protocol call only.
  4. HttpServlet class provide more common life cycle methods, that is doPost() and doGet(). If you access the servlet with HTTP Post method, then doPost() method is invoked, else the doGet() method is invoked.
  5. All above class or interface provide method to get ServletConfig and ServletContext object, ServletConfig can be used to get servlet configuration data such as init parameters and ServletContext can be used to communicate with the container.
  6. One servlet has one ServletConfig object, One web application has only one ServletContext object.
  7. If you want to learn more about servlet, please read servlet section of Java EE Tutorial.
6. Please list the general functions that servlet container provide?

Servlet container is a container where Servlet run in. It provide below functions that support Servlet to execute.

  1. Low Level Communication Support: Client web browser will communicate with the servlet container, and then container pass the request to the servlet. We do not need to care about socket communication, extract request data, encapsulate response data etc. All these low level tasks will be performed by the servlet container. We just need to care about the business logic code wrote in servlet.
  2. Life cycle Management: Servlet container manange the whole life cycle of servlet. From loading, initializing, invoke to destroy.
  3. Multiple Thread Support: For each servlet request, container will create a new thread to execute the servlet code. This can increase the efficiency and save memory and time. So servlet is not thread safe, you need to care about this. You had better use ThreadLocal to store thread related object.
7. Please Describe ServletContext, ServletConfig and their difference.

javax.servlet.ServletContext is an interface that can be used in servlet to get web application scope parameters such as web application init parameters configured in web.xml <context-param> xml element. One web application ( war file ) can only has one ServletContext object. All servlets in the web application can use their getServletContext() method to get it.

READ :   ServletRequest To Get Request Data

javax.servlet.ServletConfig is an interface that is used by a single Servlet. One Servlet has it’s own ServletConfig object. It is initiated and managed by the container. It can be used to get Servlet init parameters value from web.xml file.

The difference between ServletContext and ServletConfig.

  1. ServletContext is application scope, one web application has only one ServletContext object. It can be accessed and shared between all servlets in one web application. We can use it to get application level init parameters. We can also set attribute in it in one servlet, and get the attribute value out in other servlets.
  2. ServletCong is servlet scope, one servlet has it’s own ServletConfig object. It can be used to read out the servlet init parameters from web.xml. We can not set attribute in it.

You can learn more from article ServletConfig Vs ServletContext .

8. Tell something about RequestDispatcher?

We can use HttpServletRequest.getRequestDispatcher(String targetUrl) to get javax.servlet.RequestDispatcher interface. It has below two methods.

  1. void forward(ServletRequest req, ServletResponse resp) : Forward current request to html,jsp or other servlets in the same web application.
  2. void include(ServletRequest req, ServletResponse resp) : Include the html, jsp or other servlet’s output in the reponse.

We can use HttpServletRequest.setAttribute(String attName, String attValue) to set one variable in the request from current servlet and use HttpServRequest.getAttribute(String attName) to get the variable value in the forwarded or included jsp or servlet.

RequestDispatcher can only access same web application resources. If you want to forward to the url outside current web application, you should use HttpServletResponse.sendRedirect(String targetUrl).

9. Difference between HttpServlet and GenericServlet.
  1. HttpServlet is special for HTTP protocol.
  2. GenericServlet is protocol independent. It implement Servlet interface.
  3. HttpSerlvlet extends GenericServlet.
  4. In web application, we always extend HttpServlet.
  5. HttpServlet provide HTTP protocol specific methods such as doGet(), doPost() etc.
10. What the purpose of service() method in servlet?
  1. For GenericSerlvet, you should implement service() method to run the business logic.
  2. For HttpServlet, you do not need to write any java code in it, you just need to implement doGet() or doPost(), service() method just transfer the request to doGet() or doPost() based on the HTTP request method.
  3. If you want to run some function before doGet() or after doPost(), you can use servlet filter or listener.
11. How to initialize and release resources in servlet?
  1. Override servlet init() method, write resource initialization code in it.
  2. Generally we do open database connection, read servlet init parameter, read web application init parameter, read configure file( such as db connection settings file) actions in it.
  3. Override servlet destroy() method, write resource release code in it.
  4. We can close database connection, write to log files, release file handler in it.
12. What is the purpose of SingleThreadModel interface?
  1. SingleThreadModel interface is used to make sure the servlet execute only one single thread per request.
  2. It is used to resolve thread safety issues. But it is inefficiency.
  3. But it has been deprecated since Servlet 2.4. Because it still can not resolve some thread issue such as static variable and session attributes which can still accessed by multiple request.
  4. You just need to implement it to make it take effect, do not need to override any method.
13. How to avoid deadlock issue in servlet?
  1. Because servlet support multiple thread and not thread safe, so it is better not create other thread object in it. Because multiple thread can cause deadlock easily.
  2. If you really need thread operation and want thread safe, you had better use ThreadLocal to save thread specific object.
  3. Please do not call doGet() in doPost() and call doPost() in doGet() at the same time, this will also cause deadlock.
14. Distinguish the deference between ServletOutputStream and PrintWriter.
  1. ServletOutputStream is used to write java byte array data to the response.
  2. PrintWriter is used to write character data such as String or char array to the response.
  3. If you want to write a String to response using ServletOutputStream, you need to convert the String to a byte array data first.
  4. HttpServletResponse.getWriter() method is used to get the PrintWriter object.
  5. HttpServletResponse.getOutputStream() method is used to get the ServletOutputStream object.
  6. You can not get PrintWriter and ServletOutputStream object in same servlet method, otherwise a runtime exception java.lang.IllegalStateException will be thrown.
15. How to implement internal servlet communication?
  1. Internal servlet communication point to invoke another servlet in same web application.
  2. We can use RequestDispatcher to forward or include those servlet. Please see question 8.
16. How to make servlet thread safe?
  1. init() and destroy() method are thread safe because they are invoked only once when servlet start or stop.
  2. doGet() and doPost() method are not thread safe, because every servlet request will execute them in a single thread.
  3. The variables declared in doGet() and doPost() method are thread safe because they are thread local variable.
  4. You can also make a thread local variable by set the variable in ThreadLocal object, this is thread specific, so it is thread safe.
  5. If you update servlet instance variable or shared variable in doGet() or doPost(), you should synchronize the code to make it thread safe.
17. What is the scope of servlet attributes? 
  1. Servlet attribute is used for inner data exchange inside one web application. You can set attribute in one servlet and get it in another, you can even remove it if you need.
  2. There has three servlet attribute scope, they are: request scope, session scope and application scope. From the literal sense you can know that request scope servlet attribute is only valid in one HttpServletRequest, session scope attribute is valid only during one HttpSession and application scope attribute is valid throughout the web application.
  3. HtttpServletRequest, HttpSession and ServletContext provide set / get / remove method to manipulate related scope attribute.
READ :   ServletConfig Vs ServletContext
18. How to invoke another servlet in same web application servlet?
  1. RequestDispatcher forward() method can be used to forward process to another servlet in same web application.
  2. It also has a include() method which can be used to include another servlet’s output data in current response.
19. How to call another servlet in other web application? 
  1. RequestDispatcher can not be used to forward or include resources outside current web application.
  2. We can use HttpServletResponse sendRedirect() method to call resources (such as serlcet, jsp) from different web application.
  3. You should give sendRedirect() method a complete url (ie : http://www.google.com, https://www.yahoo.com/testabc.html).
  4. sendRedirect() method will return http status code 302 to the request client, http status code 302 means redirect, then client will be redirected to the specified url.
  5. If you want to pass some data to the target resource, you can add the data in the request parameter of the url, or you can use cookie to transfer data.
20. Please describe servlet life cycle phases.
  1. Servlet Loading : Container is responsible for loading servlet instance when container start or a request to servlet. This is configured in web.xml file.
  2. Servlet Initialization : After loading, container will invoke servlet’s init() method to initialize it. You can read init parameters from web.xml in it. Generally we do below actions in that mehtod, such as open database connection, read configuration file etc.
  3. Handling Client Request : Then it is ready to wait for client to request. When a client request is coming, container will create a new thread and execute doGet() or doPost() method in that thread to response to it.
  4. Destroy Servlet : When container stop or web application stop, container will run it’s destroy() method. You can release resource in this method(such as close database connection, write data to file, close socket etc).
21. init() vs init(ServletConfig config).
  1. init() method is generally used to write java code to do resource initialization task.
  2. If you want to use init(ServletConfig config) to initialize resource, please remember you should call super.init(config); at the first line, this will ensure that super class has been initialized first.
    init() vs init(ServletConfig config)
22. URL Encoding?
  1. URL encoding is the method to convert special characters in url to a standard utf-8 format data. This can avoid data parse errors when transfer different language data in url as parameters.
  2. java.net.URLEncoder.encode(String str, String charset) : is used to encode str to charset format.
  3. java.net.URLDecoder.decode(String str, String charset) : is used to decode an encoded string use charset encode format when a servlet receive a request parameter.
  4. For example, url http://www.baidu.com/?name=特朗普 will be encoded to http://www.baidu.com/?name=%E7%89%B9%E6%9C%97%E6%99%AE. As you can see, the chinese word 特朗普 has been encoded to utf-8 formated data.
  5. When a servlet receive the request, it can use URLDecoder.decode() method to convert %E7%89%B9%E6%9C%97%E6%99%AE to chinese word 特朗普 again.
23. What is session and how to manage servlet session? 
  1. Session is a period of time that client and server talk to each other. There can has multiple request and response between same and unique client wi the server.
  2. Since HTTP protocol is stateless, then if you want to track and manage a session, you need to add a unique data (ie : session id) between each client request and response. Then you can use the unique data (session id) to identify the request client.
  3. To save and transfer the session related data ( session id, session attribute etc )We can use Html form hidden field, Cookies, URL Rewriting and HttpSession object.
24. How to manipulate Cookies in HttpServlet?
  1. Cookie is a small piece of text data that saved at client local machine.
  2. Cookie is send by server side program, it is not a java concept, it can be generated by any server side web program such as CGI, ASP, PHP etc.
  3. Cookie can be used to communicate between client and server, when client make a request to the server, it will send the cookie data in http request header. When the server response to the client, it can add new or modify exist cookie data in response.
  4. You can use javax.servlet.http.Cookie to create a new cookie object in servlet code. It is Serializable and Cloneable.
  5. HttpServletRequest getCookies() method can be used to get an array of javax.servlet.http.Cookie object. It will return all the cookie data send by the client request.
  6. HttpServletResponse addCookie(Cookie cookie) can be used to add a new Cookie in response.
25. How to implement URL Rewriting?
  1. HttpSession use cookie to manage session attribute by default. But how to do if client disable cookie? Then URL Rewriting come into stage.
  2. All the session attribute data will be encoded and added in page url as parameter when use URL Rewriting.
  3. HttpServletResponse.encodeURL() can be used to encode url, and HttpServletResponse.encodeRedirectURL() can be used to encode the url to resources outside current web application and add session attribute data.
26. How to make a session scope object notified when session is time out or invalidate?
  1. The object should implement javax.servlet.http.HttpSessionBindingListener interface to make notifiable to session destroy event.
  2. You should override HttpSessionBindingListener.valueBound() and HttpSessionBindingListener.valueUnbound() method.
  3. The java logic code in valueBound() will be invoked when the object instance is added to session attribute. While the java code in valueUnbound() will be invoked when the session is destroyed.

 

(Visited 223 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.