In this page,we will learn about frequently asked Java Servlet Interview questions and answers for J2EE programmer.Here you can find list of Servlet interview questions, every Java Developer must have knowledge on these questions which i am going to write. As a senior java developer you can expect Servlet interview questions in technical interview.So, before attend the interview brush up these questions.
1) What is Servlet?
Ans: Servlet is a server side program that runs within a web server and serves the client request. Servlet can receive and respond the request from the web clients working on client-server protocol.The main purpose of servlet is when ever client send the request server response to it.
2) What is Servlet Container?
Ans: The servlet container is a part of web server(or) application server that provides network services over which request or responses are sent,decode MIME based requests and format MIME based responses, A servlet container also contains and manages servlets through their life cycle.
A servlet container can be built into a host web server,all servlet containers must support HTTP as a protocol for requests and responses,but additional request/response based protocols such as HTTPS(HTTP over SSL) may be supported.
3) What is difference between Server and Container?
Ans: A Server provides many services to the clients, A server many contain one or more containers such as EJB container,servlet/jsp continer. Her container holds set of objects.
4) Explain Servlet Life Cycle?
And:
public void init(ServletConfig config)throws ServletException
public void service(ServletRequest req,ServletResponse resp)throws ServletException,IOExcetion
public void destroy()
Ans: A Servelet is just like an applet in the respect that it has init() method that acts as a construcor,an initialization code you need to be place in init() method,since it get called when the servlet is first loaded.
6) Can we leave init() method empty and instead can we write initialization code inside servlet constructor?
Ans: NO, because the continer passes the ServletConfig object to the servlet only when it calls the init()method.So ServletConfig will not be accessible in the constructor.
7) How can make Automatically start the Servlet?
Ans: if present, calls the servelt's service()method at the specific time. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new thread.
The value is list of 24-hours times when the servlet should be automatically executed.
To run servelt every 6 hours you could use:
<servlet servlet-name = 'test.HelloWorld'>
<run-at>0:00,6:00,12:00,18:00</run-at>
<servlet>
8) Can we store Objects in a session?
Ans:
session.setAttribute("productIdsInCart",productIdsInCart);
session.removeAttribute("productIdsInCart");
9) What is Filter in Servlet?
Ans: Filter is an object that intercepts a message between a data source and data destination,and then filters the data being passed between them. It acts as a guard,preventing undesired information from being transmitted from one point to another.
How Filter works in Servlet:
When a Servlet Container receives a reque
st for a resource, it checks whether a filter is associated with this resource, if filter is associated with the resource,the Servlet Continer routes the request to the filter instead of routing it to the resource. After processing the request it has done fallowing the three things:
1) Authentication Filter
2) Encryption Filter
3)Logging and auditing filters
4)Caching Filters
5)Image conversion Filters
6) Data compression Filters
7) Tokenizing Filter
10) Are Sevelts MultiThreaded?
Ans: YES, the Servlet Container allocates a thread for each new request for a single Servlet. Each thread of your Servlet runs as if a single user were accessing using it alone. But you can use static variables to store and present information that is common to all threads,like a hit counter for instance.
Recommended to Read: Java Security Interview Questions
11) What are Difference between GET & POST methods in Servlet?
ANS: Both Get() & post() are used to process request and response of a client.
Get() method is a part of URL, we send less amount of data through GET. The amount of information limited is 240-255 characters or 1kb length. But by using POST we can send large amount of data through hidden fields. Get is to get the posted html data whereas Post is to post html data.
12) Can i catch the Servlet Exception and give my own error message? Custom Error message?
Ans: YES, you can Servlet Errors and give custom error pages for them,but if there are exceptional conditions you can anticipate, it would be better for your application to address these directly and try to avoid them in the first place. If a Servlet relies upon system or network resources that may not be available for unexpected reasons, you can use a RequestDispatcher to forward the request to an error page.
Example:
RequestDispatcher dispatcher=null;
request.getRequestDispatcher(/err/SQL.JSP);
try{
//SQL operation
}
catch(SQLExceptin se)
{
dispatcher.forward(request,response);
}
web.xml:
<error-page>
<error-code>
HTTP error code 404
</error-code>
<exception-type>
java.lang.RuntimeException
</exception-type>
<location>
/err/RuntimeException.jsp
</location>
</error-page>
13) How can a Servlet refresh automatically if some new data has entered the database?
Ans: You can use Client side refresh are server PUSH. Here Server Push the server sends, or pushes a sequence of response pages to the client. With server push the socket connection between client and server remains open until the last page has been sent.
Example:
<META HTTP-EQUIV="Refresh" Content="5; URL=/servlet/SocketQuotes"/>
14) What is URL Rewriting in Servlet?
Ans: The URL Rewriting is a technique in which the requested URL is modified with the session ID. URL Rewriting is another way to support anonymous session tracking. By using URL Rewriting every local URL the user might click on the dynamically modified.,or rewritten or include extra information.
15) What is Hidden form Field?
Ans: Hidden Form Filds are HTML input type that are not displayed when ready by the browser. They are sent back to the server when the form that contains them is submitted.
You include hidden form filds in HTML like below:
<form action="/servlet/live cricket" METHOD="POST">
<input type=hidden Name="zip"value="94940">
<input type=hidden Name="level"value="expert">
</form>
16) How to read browser cookies from a Servlet?
Ans:
Cookie[] cookies=req.getCookies();
if(cookies!=null)
for(int i=0;i<cookies.length;i++)
{
String name=cookies[i].getName();
String value=cookies[i].getValue();
}
}
17) How to delete Cookies in Servlet?
ANS:
<%
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>
Note: You can set Maximum age of Cookie with the cookie.setMaxAge(int seconds)
'zero' means to delete the cookie.
18) what is User Authorization in Servlet?
Ans: Servlets can be use the username authorization sent to the request to keep track of user data. Servers can be set up to restrict access to HTML pages. For example, a hash table cab be set up to contain all data for a particular user. When a user makes another request the username can be used to add new item to their cart using the hashtable.
19) How can invalidate a session?
Ans: There are 5 different ways to invalidate a session.
1) HttpSession.setMaxInactiveInterval(int sec)
2) Session will automatically expire after a certain time of inactivity
3) User closes browser window
4) calling invalidate()
5) If server crashes
6) put<session-timeout> in web.xml
20) How to confirm that user's browser accepted the Cookie?
Ans: There is no direct API to directly verify that user's browser accepted the cookie. But quick alternative is, after sending the required data to user's browser,redirect the response to a different Servlet which would try to read back to the cookie. If the Servlet is able to read back the cookie,then it was successfully saved,else user has disabled the option to accept cookies.
Let me know your comments on this post and share this to your friends and keep follow me for latest updates.
1) What is Servlet?
Ans: Servlet is a server side program that runs within a web server and serves the client request. Servlet can receive and respond the request from the web clients working on client-server protocol.The main purpose of servlet is when ever client send the request server response to it.
2) What is Servlet Container?
Ans: The servlet container is a part of web server(or) application server that provides network services over which request or responses are sent,decode MIME based requests and format MIME based responses, A servlet container also contains and manages servlets through their life cycle.
A servlet container can be built into a host web server,all servlet containers must support HTTP as a protocol for requests and responses,but additional request/response based protocols such as HTTPS(HTTP over SSL) may be supported.
3) What is difference between Server and Container?
Ans: A Server provides many services to the clients, A server many contain one or more containers such as EJB container,servlet/jsp continer. Her container holds set of objects.
4) Explain Servlet Life Cycle?
And:
public void init(ServletConfig config)throws ServletException
public void service(ServletRequest req,ServletResponse resp)throws ServletException,IOExcetion
public void destroy()
- The web server when loading the servlet calls the init method once.
- Any request from client is handled by the service() method before delegating to the doxxx() methods in the case of HttpServlet. Don't give 'private' modifier for the service() method,it will give compile time error
- When your application is stopped(or) Servlet Container shut down, your servlet's destroy() method will be called.
- ServletException represents signals that some error occurred during the processing of request and container should take appropriate measure to clean up the request.
- IOException represents signals that Servlet unable to handle requests either temporarily or permanently.
Ans: A Servelet is just like an applet in the respect that it has init() method that acts as a construcor,an initialization code you need to be place in init() method,since it get called when the servlet is first loaded.
6) Can we leave init() method empty and instead can we write initialization code inside servlet constructor?
Ans: NO, because the continer passes the ServletConfig object to the servlet only when it calls the init()method.So ServletConfig will not be accessible in the constructor.
7) How can make Automatically start the Servlet?
Ans: if present, calls the servelt's service()method at the specific time. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new thread.
The value is list of 24-hours times when the servlet should be automatically executed.
To run servelt every 6 hours you could use:
<servlet servlet-name = 'test.HelloWorld'>
<run-at>0:00,6:00,12:00,18:00</run-at>
<servlet>
8) Can we store Objects in a session?
Ans:
session.setAttribute("productIdsInCart",productIdsInCart);
session.removeAttribute("productIdsInCart");
9) What is Filter in Servlet?
Ans: Filter is an object that intercepts a message between a data source and data destination,and then filters the data being passed between them. It acts as a guard,preventing undesired information from being transmitted from one point to another.
How Filter works in Servlet:
When a Servlet Container receives a reque
st for a resource, it checks whether a filter is associated with this resource, if filter is associated with the resource,the Servlet Continer routes the request to the filter instead of routing it to the resource. After processing the request it has done fallowing the three things:
- It generates the response itself and returns it to the client
- It pass on the request(modified or unmodified)to the next filter in the chain
- It routes the request to a different resource
1) Authentication Filter
2) Encryption Filter
3)Logging and auditing filters
4)Caching Filters
5)Image conversion Filters
6) Data compression Filters
7) Tokenizing Filter
10) Are Sevelts MultiThreaded?
Ans: YES, the Servlet Container allocates a thread for each new request for a single Servlet. Each thread of your Servlet runs as if a single user were accessing using it alone. But you can use static variables to store and present information that is common to all threads,like a hit counter for instance.
Recommended to Read: Java Security Interview Questions
11) What are Difference between GET & POST methods in Servlet?
ANS: Both Get() & post() are used to process request and response of a client.
Get() method is a part of URL, we send less amount of data through GET. The amount of information limited is 240-255 characters or 1kb length. But by using POST we can send large amount of data through hidden fields. Get is to get the posted html data whereas Post is to post html data.
12) Can i catch the Servlet Exception and give my own error message? Custom Error message?
Ans: YES, you can Servlet Errors and give custom error pages for them,but if there are exceptional conditions you can anticipate, it would be better for your application to address these directly and try to avoid them in the first place. If a Servlet relies upon system or network resources that may not be available for unexpected reasons, you can use a RequestDispatcher to forward the request to an error page.
Example:
RequestDispatcher dispatcher=null;
request.getRequestDispatcher(/err/SQL.JSP);
try{
//SQL operation
}
catch(SQLExceptin se)
{
dispatcher.forward(request,response);
}
web.xml:
<error-page>
<error-code>
HTTP error code 404
</error-code>
<exception-type>
java.lang.RuntimeException
</exception-type>
<location>
/err/RuntimeException.jsp
</location>
</error-page>
13) How can a Servlet refresh automatically if some new data has entered the database?
Ans: You can use Client side refresh are server PUSH. Here Server Push the server sends, or pushes a sequence of response pages to the client. With server push the socket connection between client and server remains open until the last page has been sent.
Example:
<META HTTP-EQUIV="Refresh" Content="5; URL=/servlet/SocketQuotes"/>
14) What is URL Rewriting in Servlet?
Ans: The URL Rewriting is a technique in which the requested URL is modified with the session ID. URL Rewriting is another way to support anonymous session tracking. By using URL Rewriting every local URL the user might click on the dynamically modified.,or rewritten or include extra information.
15) What is Hidden form Field?
Ans: Hidden Form Filds are HTML input type that are not displayed when ready by the browser. They are sent back to the server when the form that contains them is submitted.
You include hidden form filds in HTML like below:
<form action="/servlet/live cricket" METHOD="POST">
<input type=hidden Name="zip"value="94940">
<input type=hidden Name="level"value="expert">
</form>
16) How to read browser cookies from a Servlet?
Ans:
Cookie[] cookies=req.getCookies();
if(cookies!=null)
for(int i=0;i<cookies.length;i++)
{
String name=cookies[i].getName();
String value=cookies[i].getValue();
}
}
17) How to delete Cookies in Servlet?
ANS:
<%
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>
Note: You can set Maximum age of Cookie with the cookie.setMaxAge(int seconds)
'zero' means to delete the cookie.
18) what is User Authorization in Servlet?
Ans: Servlets can be use the username authorization sent to the request to keep track of user data. Servers can be set up to restrict access to HTML pages. For example, a hash table cab be set up to contain all data for a particular user. When a user makes another request the username can be used to add new item to their cart using the hashtable.
19) How can invalidate a session?
Ans: There are 5 different ways to invalidate a session.
1) HttpSession.setMaxInactiveInterval(int sec)
2) Session will automatically expire after a certain time of inactivity
3) User closes browser window
4) calling invalidate()
5) If server crashes
6) put<session-timeout> in web.xml
20) How to confirm that user's browser accepted the Cookie?
Ans: There is no direct API to directly verify that user's browser accepted the cookie. But quick alternative is, after sending the required data to user's browser,redirect the response to a different Servlet which would try to read back to the cookie. If the Servlet is able to read back the cookie,then it was successfully saved,else user has disabled the option to accept cookies.
Let me know your comments on this post and share this to your friends and keep follow me for latest updates.
No comments:
Post a Comment