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?
- 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.
- 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.
- 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.
- 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.
Web Application Root | |---META-INF | |---MANIFEST.MF | |---Container Resources | |---WEB-INF |---classes | |---META-INF | | |--Application Resources | |---Java .class Files and Resources | |---i18n | |---Internationalization Files | |---lib | |---Bundled JAR Files | |---tags | |---JSP Tag Files | |---tld | |---JSP Tag Library Descriptors | |---web.xml
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?
- 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.
- HTTP Post method is used to upload form data to web server while HTTP Get method is used to retrieve data from web server.
- 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.
- 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.
- Url links use Get method by default.
- Article HTTP Overview introduce all HTTP methods in detail, you can read it.
4. Explain MIME type?
- 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.
- 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?
- Java Servlet is a web component which runs in servlet container. It can produce dynamic web content.
- All Servlet class should implement interface javax.servlet.Servlet. The interface defines it’s life cycle method that is init(), destroy(), service().
- 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.
- 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.
- 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.
- One servlet has one ServletConfig object, One web application has only one ServletContext object.
- 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.
- 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.
- Life cycle Management: Servlet container manange the whole life cycle of servlet. From loading, initializing, invoke to destroy.
- 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.
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.
- 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.
- 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.
- void forward(ServletRequest req, ServletResponse resp) : Forward current request to html,jsp or other servlets in the same web application.
- 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
9. Difference between HttpServlet and GenericServlet.
- HttpServlet is special for HTTP protocol.
- GenericServlet is protocol independent. It implement Servlet interface.
- HttpSerlvlet extends GenericServlet.
- In web application, we always extend HttpServlet.
- HttpServlet provide HTTP protocol specific methods such as doGet(), doPost() etc.
10. What the purpose of service() method in servlet?
- For GenericSerlvet, you should implement service() method to run the business logic.
- 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.
- 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?
- Override servlet init() method, write resource initialization code in it.
- 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.
- Override servlet destroy() method, write resource release code in it.
- We can close database connection, write to log files, release file handler in it.
12. What is the purpose of SingleThreadModel interface?
- SingleThreadModel interface is used to make sure the servlet execute only one single thread per request.
- It is used to resolve thread safety issues. But it is inefficiency.
- 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.
- 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?
- 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.
- If you really need thread operation and want thread safe, you had better use ThreadLocal to save thread specific object.
- 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.
- ServletOutputStream is used to write java byte array data to the response.
- PrintWriter is used to write character data such as String or char array to the response.
- If you want to write a String to response using ServletOutputStream, you need to convert the String to a byte array data first.
- HttpServletResponse.getWriter() method is used to get the PrintWriter object.
- HttpServletResponse.getOutputStream() method is used to get the ServletOutputStream object.
- You can not get PrintWriter and ServletOutputStream object in same servlet method, otherwise a runtime exception
java.lang.IllegalStateExceptionwill be thrown.
15. How to implement internal servlet communication?
- Internal servlet communication point to invoke another servlet in same web application.
- We can use RequestDispatcher to forward or include those servlet. Please see question 8.
16. How to make servlet thread safe?
- init() and destroy() method are thread safe because they are invoked only once when servlet start or stop.
- doGet() and doPost() method are not thread safe, because every servlet request will execute them in a single thread.
- The variables declared in doGet() and doPost() method are thread safe because they are thread local variable.
- You can also make a thread local variable by set the variable in ThreadLocal object, this is thread specific, so it is thread safe.
- 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?
- 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.
- 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.
- HtttpServletRequest, HttpSession and ServletContext provide set / get / remove method to manipulate related scope attribute.
18. How to invoke another servlet in same web application servlet?
- RequestDispatcher forward() method can be used to forward process to another servlet in same web application.
- 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?
- RequestDispatcher can not be used to forward or include resources outside current web application.
- We can use HttpServletResponse sendRedirect() method to call resources (such as serlcet, jsp) from different web application.
- You should give sendRedirect() method a complete url (ie : http://www.google.com, https://www.yahoo.com/testabc.html).
- 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.
- 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.
- Servlet Loading : Container is responsible for loading servlet instance when container start or a request to servlet. This is configured in web.xml file.
- 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.
- 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.
- 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).
- init() method is generally used to write java code to do resource initialization task.
- 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.
22. URL Encoding?
- 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.
java.net.URLEncoder.encode(String str, String charset) : is used to encode str to charset format.
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.
- 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.
- When a servlet receive the request, it can use URLDecoder.decode() method to convert
%E7%89%B9%E6%9C%97%E6%99%AEto chinese word 特朗普 again.
23. What is session and how to manage servlet session?
- 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.
- 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.
- 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?
- Cookie is a small piece of text data that saved at client local machine.
- 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.
- 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.
- You can use
javax.servlet.http.Cookieto create a new cookie object in servlet code. It is Serializable and Cloneable.
HttpServletRequest getCookies()method can be used to get an array of
javax.servlet.http.Cookieobject. It will return all the cookie data send by the client request.
HttpServletResponse addCookie(Cookie cookie)can be used to add a new Cookie in response.
25. How to implement URL Rewriting?
- HttpSession use cookie to manage session attribute by default. But how to do if client disable cookie? Then URL Rewriting come into stage.
- All the session attribute data will be encoded and added in page url as parameter when use URL Rewriting.
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?
- The object should implement
javax.servlet.http.HttpSessionBindingListenerinterface to make notifiable to session destroy event.
- You should override
- 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.