Hi Friends In this post we would like to share you commonly asked J2EE interview questions.
Q)What is Servlet
Servlet is server side component, a servlet is small plug gable extension to the server and servlets are used to extend the functionality of the java-enabled server. Servlets are durable objects means that they remain in memory specially instructed to be destroyed. Servlets will be loaded in the Address space of web server.
->Servlet are loaded 3 ways
1) When the web sever starts
2) You can set this in the configuration file
3) Through an administration interface.
Q) What is Temporary Servlet?
When we sent a request to access a JSP, servlet container internally creates a 'servlet' & executes it. This servlet is called as 'Temporary servlet'. In general this servlet will be deleted immediately to create & execute a servlet base on a JSP we can use following command.
Java weblogic.jspc—keepgenerated *.jsp
Q) What is the difference between Server and Container?
A) A server provides many services to the clients, A server may contain one or more containers such as ejb containers,servlet/jsp container. Here a container holds a set of objects.
Q)What is Servlet Container
The servlet container is a part of a Web server (or) Application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses.
1) A servlet container also contains and manages servlets through their lifecycle.
2) A servlet container can be built into a host Web server, or installed as an add-on component to a Web Server via that server‘s native extension API.
3)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.
Q) Generally Servlets are used for complete HTML generation. If you want to generate partial HTML's that include some static text as well as some dynamic text, what method do you use?
Using 'RequestDispather.include(―xx.html‖) in the servlet code we can mix the partial static HTML Directory page.
Ex: - RequestDispatcher rd=ServletContext.getRequestDispatcher(―xx.html‖);
rd.include(request,response);
Q) Can you explain Servlet Life cycle
Life Cycle sates: new born state, ready state, running state, Idle/wait and dead
Below are the life cycle methods of servlet.
Public void init (ServletConfig config) throws ServletException
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy ()
a) The Web server when loading the servlet calls the init method once. (The init method typically establishes database
connections.)
b)Any request from client is handled initially by the service () method before delegating to the doXxx () methods in the
case of HttpServlet. If u put ―Private‖ modifier for the service() it will give compile time error.
c) When your application is stopped (or) Servlet Container shuts down, your Servlet's destroy () method will be called.
This allows you to free any resources you may have got hold of in your Servlet's init () method, this will call only once.
ServletException :Signals that some error occurred during the processing of the request and the container should
take appropriate measures to clean up the request.
IOException : Signals that Servlet is unable to handle requests either temporarily or permanently.
Q) Why there is no constructor in servlet?
A servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should e place in the init(), since it get called when the servlet is first loaded.
Q) Can we use the constructor, instead of init(), to initialize servlet?
Yes, of course you can use. There‘s nothing to stop you. But you shouldn‘t. The original reason for init() was that ancient versions of Java couldn‘t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won‘t have access to a ServletConfig or ServletContext.
Q) Can we leave init() method empty and insted can we write initilization code inside servlet's constructor?
No, because the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.
Q) Explain ServletConfig Interface & ServletContex Interfaces
ServletConfig : ServletConfig object is used to obtain configuration data when it is loaded. There can be multiple ServletConfig objects in a single web application.
This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.
Ex:-
<web-app>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
<init-param>
<param-name>driverclassname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>dburl</param-name>
<param-value>jdbc:odbc:MySQLODBC</param-value>
</init-param>
</servlet>
</web-app>
--------------------------------------
public void init()
{
ServletConfig config = getServletConfig();
String driverClassName = config.getInitParameter("driverclassname");
String dbURL = config.getInitParameter("dburl");
Class.forName(driverClassName);
dbConnection = DriverManager.getConnection(dbURL,username,password);
}
ServletContext: ServletContext is also called application object. ServletContext is used to obtain information about environment on which a servlet is running.
There is one instance object of the ServletContext interface associated with each Web application deployed into a container. In cases where the container is distributed over many virtual machines, a Web application will have an instance of the ServletContext for each JVM.
Servlet Context is a grouping under which related servlets run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container.
Q) How to add application scope in Servlets?
In Servlets Application is nothing but ServletContext Scope.
ServletContext appContext = servletConfig.getServletContext();
appContext.setAttribute(paramName, req.getParameter(paramName));
appContext.getAttribute(paramName);
Q) Diff between HttpSeassion & Stateful Session bean? Why can't HttpSessionn be used instead of of Session bean?
HttpSession is used to maintain the state of a client in webservers, which are based on Http protocol. Where as
Stateful Session bean is a type of bean, which can also maintain the state of the client in Application servers, based on RMI-IIOP.
Q) Can we store objects in a session?
session.setAttribute("productIdsInCart",productIdsInCart);
session.removeAttribute("productIdsInCart");
Q) Are Servlets multithread?(This is most important question)
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 u can use static variable to store and present information that is common to all threads, like a hit counter for instance.
Q) what is Session Tracking ?
Session tracking is the capability of the server to maintain the single client sequential list.
Q) what us Servlet chaining?
Is a technique in which two are more servlets cooperating in servicing a single client sequential request, where one servlet output is piped to the next servlet output. The are 2 ways
(i) Servlet Aliasing (ii) HttpRequest
Servlet Aliasing : allow you to setup a single alias name for a comma delimited list of servlets. To make a servlet chain open your browser and give the alias name in URL.
HttpRequest: construct a URL string and append a comma delimited list of servlets to the end.
Q)What is HttpTunnelling
Is a method used to reading and writing serializes objects using a http connection. You are creating a sub protocol inside http protocol that is tunneling inside another protocol.
Q) Diff GET & POST (This is most important question)
* GET & POST are used to process request and response of a client.
* GET method is the part of URL, we send less amount of data through GET. The amount of information limited is 240-255 characters (or 1kb in length).
*Using POST we can send large amount of data through hidden fields.
* Get is to get the posted html data, POST is to post the html data.
Q) Diff Http & Generic Servlet (This is most important question)
* HttpServlet class extends Generic servlet , so Generic servlet is parent and HttpServlet is child.
* Generic is from javax.servlet package, HttpServlet is from javax.servlet.Http package.
* Http implements all Http protocols, Generic servlet will implements all networking protocol
* Http is stateless protocol, which mean each request is independent of previous one, In generic we cannot maintain the state of next page only main state of current page.
* A protocol is said to be stateless if it has n memory of prior connection.
* Http servlet extra functionality is capable of retrieving Http header information.
*Http servlet can override doGet(), doDelete(), doGet(), doPost(), doTrace(), generic servlet will override Service() method only.
Q)What are all various types of Session tracking Techniques
Below are the various session tracking techniques in servlets
(i) URL Rewriting
(ii) Hidden form Field
(iii) Persistence Cookies
(iv) Session Tracking API
(v) User Authorization
URL RewritingURL 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. With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information.
http://server:port/servlet/Rewritten?sessionid=123 added parameter
Hidden form Field
Hidden form fields are HTML input type that are not displayed when read by the browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this:
<FORM ACTION="/servlet/TrainFinder" METHOD="POST">
<INPUT TYPE=hidden NAME="trainNumeber" VALUE="94040">
<INPUT TYPE=hidden NAME="station" VALUE="expert">
</FORM>
In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.
Persistence Cookie
A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser.
When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server, subject to certain rules. Because a cookie's value can uniquely identify a client, cookies are often used for session tracking. Because cookies are sent using HTTP headers, they should be added to the response before you send any content. Browsers are only required to accept 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.
Session Tracking API
In Java the javax.servlet.http.HttpSession API handles many of the details of session tracking. It allows a session object to be created for each user session, then allows for values to be stored and retrieved for each session.
A session object is created through the HttpServletRequest using the getSession() method:
HttpSession session = request.getSession(true);
This will return the session for this user or create one if one does not already exist. Values can be stored for a user session using the HttpSession method putValue():
session.putValue("valueName", valueObject);
Session objects can be retrieved using getValue(String name), while a array of all value names can be retrieved using getValueNames().
Values can also be removed using removeValue(String valueName)
User Authorization
Servers can be set up to restrict access to HTML pages (and servlets). The user is required to enter a user name and password. Once they are verified the client re-sends the authorisation with requests for documents to that site in the http header.
Servlets can use the username authorisation sent with request to keep track of user data. For example, a hashtable can be set up to contain all the data for a particular user. When a user makes another request the user name can be used to add new items to their cart using the hashtable.
Q)What is Servlet
Servlet is server side component, a servlet is small plug gable extension to the server and servlets are used to extend the functionality of the java-enabled server. Servlets are durable objects means that they remain in memory specially instructed to be destroyed. Servlets will be loaded in the Address space of web server.
->Servlet are loaded 3 ways
1) When the web sever starts
2) You can set this in the configuration file
3) Through an administration interface.
Q) What is Temporary Servlet?
When we sent a request to access a JSP, servlet container internally creates a 'servlet' & executes it. This servlet is called as 'Temporary servlet'. In general this servlet will be deleted immediately to create & execute a servlet base on a JSP we can use following command.
Java weblogic.jspc—keepgenerated *.jsp
Q) What is the difference between Server and Container?
A) A server provides many services to the clients, A server may contain one or more containers such as ejb containers,servlet/jsp container. Here a container holds a set of objects.
Q)What is Servlet Container
The servlet container is a part of a Web server (or) Application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses.
1) A servlet container also contains and manages servlets through their lifecycle.
2) A servlet container can be built into a host Web server, or installed as an add-on component to a Web Server via that server‘s native extension API.
3)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.
Q) Generally Servlets are used for complete HTML generation. If you want to generate partial HTML's that include some static text as well as some dynamic text, what method do you use?
Using 'RequestDispather.include(―xx.html‖) in the servlet code we can mix the partial static HTML Directory page.
Ex: - RequestDispatcher rd=ServletContext.getRequestDispatcher(―xx.html‖);
rd.include(request,response);
Q) Can you explain Servlet Life cycle
Life Cycle sates: new born state, ready state, running state, Idle/wait and dead
Below are the life cycle methods of servlet.
Public void init (ServletConfig config) throws ServletException
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy ()
a) The Web server when loading the servlet calls the init method once. (The init method typically establishes database
connections.)
b)Any request from client is handled initially by the service () method before delegating to the doXxx () methods in the
case of HttpServlet. If u put ―Private‖ modifier for the service() it will give compile time error.
c) When your application is stopped (or) Servlet Container shuts down, your Servlet's destroy () method will be called.
This allows you to free any resources you may have got hold of in your Servlet's init () method, this will call only once.
ServletException :Signals that some error occurred during the processing of the request and the container should
take appropriate measures to clean up the request.
IOException : Signals that Servlet is unable to handle requests either temporarily or permanently.
Q) Why there is no constructor in servlet?
A servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should e place in the init(), since it get called when the servlet is first loaded.
Q) Can we use the constructor, instead of init(), to initialize servlet?
Yes, of course you can use. There‘s nothing to stop you. But you shouldn‘t. The original reason for init() was that ancient versions of Java couldn‘t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won‘t have access to a ServletConfig or ServletContext.
Q) Can we leave init() method empty and insted can we write initilization code inside servlet's constructor?
No, because the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.
Q) Explain ServletConfig Interface & ServletContex Interfaces
ServletConfig : ServletConfig object is used to obtain configuration data when it is loaded. There can be multiple ServletConfig objects in a single web application.
This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.
Ex:-
<web-app>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
<init-param>
<param-name>driverclassname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>dburl</param-name>
<param-value>jdbc:odbc:MySQLODBC</param-value>
</init-param>
</servlet>
</web-app>
--------------------------------------
public void init()
{
ServletConfig config = getServletConfig();
String driverClassName = config.getInitParameter("driverclassname");
String dbURL = config.getInitParameter("dburl");
Class.forName(driverClassName);
dbConnection = DriverManager.getConnection(dbURL,username,password);
}
ServletContext: ServletContext is also called application object. ServletContext is used to obtain information about environment on which a servlet is running.
There is one instance object of the ServletContext interface associated with each Web application deployed into a container. In cases where the container is distributed over many virtual machines, a Web application will have an instance of the ServletContext for each JVM.
Servlet Context is a grouping under which related servlets run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container.
Q) How to add application scope in Servlets?
In Servlets Application is nothing but ServletContext Scope.
ServletContext appContext = servletConfig.getServletContext();
appContext.setAttribute(paramName, req.getParameter(paramName));
appContext.getAttribute(paramName);
Q) Diff between HttpSeassion & Stateful Session bean? Why can't HttpSessionn be used instead of of Session bean?
HttpSession is used to maintain the state of a client in webservers, which are based on Http protocol. Where as
Stateful Session bean is a type of bean, which can also maintain the state of the client in Application servers, based on RMI-IIOP.
Q) Can we store objects in a session?
session.setAttribute("productIdsInCart",productIdsInCart);
session.removeAttribute("productIdsInCart");
Q) Are Servlets multithread?(This is most important question)
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 u can use static variable to store and present information that is common to all threads, like a hit counter for instance.
Q) what is Session Tracking ?
Session tracking is the capability of the server to maintain the single client sequential list.
Q) what us Servlet chaining?
Is a technique in which two are more servlets cooperating in servicing a single client sequential request, where one servlet output is piped to the next servlet output. The are 2 ways
(i) Servlet Aliasing (ii) HttpRequest
Servlet Aliasing : allow you to setup a single alias name for a comma delimited list of servlets. To make a servlet chain open your browser and give the alias name in URL.
HttpRequest: construct a URL string and append a comma delimited list of servlets to the end.
Q)What is HttpTunnelling
Is a method used to reading and writing serializes objects using a http connection. You are creating a sub protocol inside http protocol that is tunneling inside another protocol.
Q) Diff GET & POST (This is most important question)
* GET & POST are used to process request and response of a client.
* GET method is the part of URL, we send less amount of data through GET. The amount of information limited is 240-255 characters (or 1kb in length).
*Using POST we can send large amount of data through hidden fields.
* Get is to get the posted html data, POST is to post the html data.
Q) Diff Http & Generic Servlet (This is most important question)
* HttpServlet class extends Generic servlet , so Generic servlet is parent and HttpServlet is child.
* Generic is from javax.servlet package, HttpServlet is from javax.servlet.Http package.
* Http implements all Http protocols, Generic servlet will implements all networking protocol
* Http is stateless protocol, which mean each request is independent of previous one, In generic we cannot maintain the state of next page only main state of current page.
* A protocol is said to be stateless if it has n memory of prior connection.
* Http servlet extra functionality is capable of retrieving Http header information.
*Http servlet can override doGet(), doDelete(), doGet(), doPost(), doTrace(), generic servlet will override Service() method only.
Q)What are all various types of Session tracking Techniques
Below are the various session tracking techniques in servlets
(i) URL Rewriting
(ii) Hidden form Field
(iii) Persistence Cookies
(iv) Session Tracking API
(v) User Authorization
URL RewritingURL 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. With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information.
http://server:port/servlet/Rewritten?sessionid=123 added parameter
Hidden form Field
Hidden form fields are HTML input type that are not displayed when read by the browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this:
<FORM ACTION="/servlet/TrainFinder" METHOD="POST">
<INPUT TYPE=hidden NAME="trainNumeber" VALUE="94040">
<INPUT TYPE=hidden NAME="station" VALUE="expert">
</FORM>
In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.
Persistence Cookie
A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser.
When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server, subject to certain rules. Because a cookie's value can uniquely identify a client, cookies are often used for session tracking. Because cookies are sent using HTTP headers, they should be added to the response before you send any content. Browsers are only required to accept 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.
Session Tracking API
In Java the javax.servlet.http.HttpSession API handles many of the details of session tracking. It allows a session object to be created for each user session, then allows for values to be stored and retrieved for each session.
A session object is created through the HttpServletRequest using the getSession() method:
HttpSession session = request.getSession(true);
This will return the session for this user or create one if one does not already exist. Values can be stored for a user session using the HttpSession method putValue():
session.putValue("valueName", valueObject);
Session objects can be retrieved using getValue(String name), while a array of all value names can be retrieved using getValueNames().
Values can also be removed using removeValue(String valueName)
User Authorization
Servers can be set up to restrict access to HTML pages (and servlets). The user is required to enter a user name and password. Once they are verified the client re-sends the authorisation with requests for documents to that site in the http header.
Servlets can use the username authorisation sent with request to keep track of user data. For example, a hashtable can be set up to contain all the data for a particular user. When a user makes another request the user name can be used to add new items to their cart using the hashtable.
0 comments:
Feel Free to Share your Feeling about these content