Java_J2EE_Job_Interview_Companion
.pdf110 |
Enterprise – Servlet |
Q. What are the different scopes or places where a servlet can save data for its processing? Data saved in a request-scope goes out of scope once a response has been sent back to the client (i.e. when the request is completed).
//save and get request-scoped value
request.setAttribute(“calc-value”, new Float(7.0)); request.getAttribute(“calc-value”);
Data saved in a session-scope is available across multiple requests. Data saved in the session is destroyed when the session is destroyed (not when a request completes but spans several requests).
//save and get session-scoped value
HttpSession session = request.getSession(false); If(session != null) {
session.setAttribute(“id”, “DX12345”); value = session.getAttribute(“id”);
}
Data saved in a ServletContext scope is shared by all servlets and JSPs in the context. The data stored in the servlet context is destroyed when the servlet context is destroyed.
//save and get an application-scoped value
getServletContext().setAttribute(“application-value”, “shopping-app”); value = getServletContext().getAttribute(“application-value”);
Q. Which code line should be set in a response object before using the PrintWriter or the OutputStream? You need to set the content type using the setContentType(…) method.
//to return an html response.setContentType(“text/html”); PrintWriter out = response.getWriter(); out.println(“…….”);
//to return an image response.setContentType(“image/gif”);
How does a Servlet differ from an Applet?
|
Applet |
Servlet |
|
Applets execute on a browser. |
Servlets execute within a web container in an Application Server. |
|
Applets have a graphical user interface. |
Servlets do not have a graphical user interface. |
|
|
|
Q 10: HTTP is a stateless protocol, so, how do you maintain state? How do you store user data between requests? SF
PIBP FAQ
A 10: This is a commonly asked interview question. The “http protocol” is a stateless request/response based protocol. You can retain the state information between different page requests as follows:
HTTP Sessions are the recommended approach. A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable. In a Java servlet the session can be obtained as follows: CO
HttpSession session = request.getSession(true); //returns a current session or a new session
//To put/get a value in/from the session
Name name = new Name(“Peter”);
session.setAttribute(“Firstname”, name); //session.putValue(…) is deprecated as of 2.2
session.getAttribute(“Firstname”);//get a value. session.getValue(…) is deprecated
//If a session is no longer required e.g. user has logged out, etc then it can be invalidated. session.invalidate();
//you can also set the session inactivity lease period on a per session basis session.setMaxInactiveInterval(300);//resets inactivity period for this session as 5 minutes
112 |
Enterprise – Servlet |
Sessions can be timed out (configured in web.xml) or manually invalidated.
Hidden Fields on the pages can maintain state and they are not visible on the browser. The server treats both hidden and non-hidden fields the same way.
<INPUT type=”hidden” name=”Firstname” value=”Peter”> <INPUT type=”hidden” name=”Lastname” value=”Smith”>
The disadvantage of hidden fields is that they may expose sensitive or private information to others.
URL re-writing will append the state information as a query string to the URL. This should not be used to maintain private or sensitive information.
Http://MyServer:8080/MyServlet?Firstname=Peter&Lastname=Smith
Cookies: A cookie is a piece of text that a Web server can store on a user’s hard disk. Cookies allow a website to store information on a user’s machine and later retrieve it. These pieces of information are stored as name-value pairs. The cookie data moves in the following manner:
If you type the URL of a website into your browser, your browser sends the request to the Web server. When the browser does this it looks on your machine for a cookie file that URL has set. If it finds it, your browser will send all of the name-value pairs along with the URL. If it does not find a cookie file, it sends no cookie data.
The URL’s Web server receives the cookie data and requests for a page. If name-value pairs are received, the server can use them. If no name-value pairs are received, the server can create a new ID and then sends name-value pairs to your machine in the header for the Web page it sends. Your machine stores the name value pairs on your hard disk.
Cookies can be used to determine how many visitors visit your site. It can also determine how many are new versus repeated visitors. The way it does this is by using a database. The first time a visitor arrives; the site creates a new ID in the database and sends the ID as a cookie. The next time the same user comes back, the site can increment a counter associated with that ID in the database and know how many times that visitor returns. The sites can also store user preferences so that site can look different for each visitor.
Q. How can you set a cookie and delete a cookie from within a Servlet?
//to add a cookie
Cookie myCookie = new Cookie(“aName”, “aValue”); response.addCookie(myCookie);
//to delete a cookie myCookie.setValue(“aName”, null); myCookie.setMax(0); myCookie.setPath(“/”); response.addCookie(myCookie);
Q. Which mechanism to choose?
State |
|
Description |
||
mechanism |
|
|
|
|
HttpSession |
|
|
There is no limit on the size of the session data kept. |
|
|
|
|
The performance is good. |
|
|
|
|
This is the preferred way of maintaining state. If we use the HTTP session with the application server’s |
|
|
|
|
persistence mechanism (server converts the session object into BLOB type and stores it in the |
|
|
|
|
Database) then the performance will be moderate to poor. |
|
|
|
|
When using HttpSession mechanism you need to take care of the following points: |
|
|
|
Note: |
||
|
|
|
Remove session explicitly when you no longer require it. |
|
|
|
|
Set the session timeout value. |
|
|
|
|
Your application server may serialize session objects after crossing a certain memory limit. This is |
|
|
|
|
expensive and affects performance. So decide carefully what you want to store in a session. |
|
|
|
|
|
|
Hidden fields |
|
|
There is no limit on size of the session data. |
|
|
|
|
May expose sensitive or private information to others (So not good for sensitive information). |
|
|
|
|
The performance is moderate. |
|
URL rewriting |
|
|
There is a limit on the size of the session data. |
114 |
Enterprise – Servlet |
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException
{
…
//3. create a remote or a local interface
MyBean bean = home.create();
//4. Now you can call business method on remote interface bean.invokeBusinessMethod(…);
}
Q. Is it possible to share an HttpSession between a Servlet/JSP and EJB? You can pass an HttpSession as a parameter to an EJB method only if all objects in session are serializable. This is because they are “passed-by- value” and if any values in the HttpSession are altered inside the EJB then it won’t be reflected back to the HttpSession in the Servlet.
Even though it is possible to pass an HttpSession object, it is a bad practice in terms of design because you are unnecessarily coupling your presentation tier (i.e. Servlet/JSP) object with your business-tier (i.e. EJB) objects. So rather than passing the whole, large HttpSession create a class (i.e. Plain Old Java Object) that acts as a value object (aka Data Transfer Object – refer Q85 in Enterprise section) that holds all the data you need to pass back and forth between your presentation tier and business tier. This approach would also be flexible enough to handle a scenario where your EJBs in the business tier need to support a non-http based client like a stand alone Java application or a WAP client.
Q. How does an HTTP Servlet handle client requests? All client requests are handled through the service() method. The service method dispatches the request to an appropriate method like doGet(), doPost() etc to handle that request.
Q 12: |
Explain the directory structure of a Web application? SF SE |
FAQ |
|
A 12: |
Refer Q7 in Enterprise section for diagram: J2EE deployment structure and explanation in this section where |
MyAppsWeb.war is depicting the Web application directory structure. The directory structure of a Web application consists of two parts:
|
Directory structure of a web application |
|
crm.war |
|
|
(web archive) |
|
|
|
*.jsp, *.html, *.css, *.gif |
|
public |
(can have sub-folders) |
MANIFEST.MF |
directory |
|
|
(document |
|
class-path: log4j.jar MyAppsCommon.jar MyAppsUtil.jar |
root) |
META-INF |
|
|
web.xml |
|
|
|
|
|
|
deployment descriptor |
|
WEB-INF |
Jboss-web.xml |
|
|
application server specific deployment descriptor |
private |
|
struts.jar, crimson.jar |
directory |
lib |
|
|
3rd party jar files |
|
|
classes |
class files |
|
e.g. CRMServlet |
|
|
|
A public resource directory (document root): The document root is where JSP pages, client-side classes and archives, and static Web resources are stored.
A private directory called WEB-INF: which contains following files and directories:
web.xml: Web application deployment descriptor.
application server specific deployment descriptor e.g. jboss-web.xml etc.
*.tld: Tag library descriptor files.
classes: A directory that contains server side classes like servlets, utility classes, JavaBeans etc.
lib: A directory where JAR (archive files of tag libraries, utility libraries used by the server side classes) files are stored.
Enterprise – Servlet |
115 |
Note: JSP resources usually reside directly or under subdirectories of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files from direct access. Refer Q35 in Enterprise section.
Q 13: What is the difference between doGet () and doPost () or GET and POST? SFSE FAQ
A 13: Prefer using doPost() because it is secured and it can send much more information to the server..
|
GET or doGet() |
|
|
POST or doPost() |
||
|
The request parameters are transmitted as a query string |
|
The request parameters are passed with the body of the |
|||
|
appended to the request. All the parameters get appended to |
|
request. |
|||
|
the URL in the address bar. Allows browser bookmarks but not |
|
More secured. In HTML you can specify as follows: |
|||
|
appropriate for transmitting private or sensitive information. |
|
||||
|
|
|
|
|
|
|
|
http://MyServer/MyServlet?name=paul |
|
|
|
<form name=”SSS” method=”POST” > |
|
|
This is a security risk. In an HTML you can specify as follows: |
|
|
|
||
|
|
|
|
|
|
|
|
<form name=”SSS” method=”GET” > |
|
|
|
|
|
|
GET was originally intended for static resource retrieval. |
|
POST was intended for form submits where the state of the |
|||
|
|
|
|
|
model and database are expected to change. |
|
|
|
|
|
|||
|
GET is not appropriate when large amounts of input data are |
|
Since it sends information through a socket back to the |
|||
|
being transferred. Limited to 1024 characters. |
|
server and it won’t show up in the URL address bar, it can |
|||
|
|
|
|
|
send much more information to the server. Unlike doGet(), it |
|
|
|
|
|
|
is not restricted to sending only textual data. It can also send |
|
|
|
|
|
|
binary data such as serialized Java objects. |
|
|
|
|
|
|
|
|
Q. If you want a servlet to take the same action for both GET and POST request, what would you do? You should have doGet call doPost, or vice versa.
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
ServletOutputStream out = resp.getOutputStream(); out.setContentType(“text/html”); out.println("<html><h1>Output to Browser</h1>");
out.println("<body>Written as html from a Servlet<body></html>");
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
doPost(req, resp); //call doPost() for flow control logic.
}
Q 14: |
What are the ServletContext and ServletConfig objects? What are Servlet environment objects? SF |
A 14: |
The Servlet Engine uses both interfaces. The servlet engine implements the ServletConfig interface in order to |
pass configuration details from the deployment descriptor (web.xml) to a servlet via its init() method.
public class CRMServlet extends HttpServlet { //initializes the servlet
public void init(ServletConfig config)throws ServletException { super.init(config);
}
…
}
ServletConfig |
ServletContext |
|
The ServletConfig parameters are for a particular |
The ServletContext parameters are specified for the entire Web |
|
Servlet. The parameters are specified in the web.xml |
application. The parameters are specified in the web.xml (i.e. |
|
(i.e. deployment descriptor). It is created after a servlet |
deployment descriptor). Servlet context is common to all Servlets. So |
|
is instantiated and it is used to pass initialization |
all Servlets share information through ServletContext. |
|
information to the servlet. |
|
|
|
|
|
Example: |
|
|
116 |
|
|
Enterprise – Servlet |
|
|
|
|
|
String strCfgPath = |
getServletConfig().getInitParameter("config"); |
|
|
String strServletName |
= getServletConfig().getServletName(); |
|
|
String strClassName |
= |
getServletContext().getAttribute("GlobalClassName"); |
Q. How can you invoke a JSP error page from a controller servlet? The following code demonstrates how an exception from a servlet can be passed to an error JSP page.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try { //doSomething
}
catch(Exception ex) {
req.setAttribute("javax.servlet.ex",ex);//store the exception as a request attribute. ServletConfig sConfig = getServletConfig();
ServletContext sContext = sConfig.getServletContext(); sContext.getRequestDispatcher("/jsp/ErrorPage.jsp").forward(req, resp);// forward the //request with the exception stored as an attribute to the “ErrorPage.jsp”. ex.printStackTrace();
}
}
Q. What are servlet lifecycle events? Servlet lifecycle events work like the Swing events. Any listener interested in observing the ServletContext lifecycle can implement the ServletContextListener interface and in the ServletContext attribute lifecycle can implement the ServletContextAttributesListener interface. The session listener model is similar to the ServletContext listener model (Refer Servlet spec 2.3 or later). ServletContext’s and Session’s listener objects are notified when servlet contexts and sessions are initialized and destroyed, as well as when attributes are added or removed from a context or session. For example: You can declare a listener in the web.xml deployment descriptor as follows:
<listener>
<listener-class>com.MyJDBCConnectionManager </listener-class> </listener>
You can create the listener class as shown below:
public class MyJDBCConnectionManager implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) { Connection con = // create a connection event.getServletContext().setAttribute("con", con);
}
public void contextDestroyed(ServletContextEvent e) {
Connection con = (Connection) e.getServletContext().getAttribute("con"); try { con.close(); } catch (SQLException ignored) { } // close connection
}
}
The server creates an instance of the listener class to receive events and uses introspection to determine what listener interface (or interfaces) the class implements.
Q 15: What is the difference between HttpServlet and GenericServlet? SF
A 15: Both these classes are abstract but:
GenericServlet |
HttpServlet |
A GenericServlet has a service() method to handle |
The HttpServlet extends GenericServlet and adds support for HTTP |
requests. |
protocol based methods like doGet(), doPost(), doHead() etc. All |
|
client requests are handled through the service() method. |
|
The service method dispatches the request to an appropriate |
|
method like doGet(), doPost() etc to handle that request. |
|
HttpServlet also has methods like doHead(), doPut(), doOptions(), |
|
doDelete(), and doTrace(). |
|
|
Protocol independent. GenericServlet is for servlets |
Protocol dependent (i.e. HTTP). |
that might not use HTTP (for example FTP service). |
|
|
|
118 |
Enterprise – Servlet |
Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null interface javax.servlet.SingleThreadedModel. The container will use one of the following approaches to ensure thread safety:
Instance pooling where container maintains a pool of servlets.
Sequential processing where new requests will wait while the current request is being processed.
Best practice: It is best practice to use multi-threading and stay away from the single threaded model of the servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized, used in readonly manner, or shared values can be stored in a session, as hidden fields or in database table. The single threaded model can adversely affect performance and hence has been deprecated in the servlet specification 2.4.
As shown in the diagram above, threads share the heap and have their own stack space (i.e. each thread has its own stack). This is how one thread’s invocation of a method (doGet(), doPost()) and its local variables (e.g. int y ) are kept thread safe from other threads. But the heap (e.g. int x ) is not thread-safe and must be synchronized for thread safety or stored in an HTTP session or stored as a hidden field. The variable “CONSTANT” is a read only immutable field since it is marked as final and hence thread-safe.
Note: How do you make a Servlet thread safe? is a popular interview question.
Q. How do you get your servlet to stop timing out on a really long database query?
There are situations despite how much database tuning effort you put into a project, there might be complex queries or a batch process initiated via a Servlet, which might take several minutes to execute. The issue is that if you call a long query from a Servlet or JSP, the browser may time out before the call completes. When this happens, the user will not see the results of their request. There are proprietary solutions to this problem like asynchronous servlets in WebLogic, Async Beans in WebSphere etc but you need a solution that is portable. Let us look at portable solutions to this issue.
Solution 1: Client-pull or client-refresh (aka server polling): You can use the <META> tag for polling the server. This tag tells the client it must refresh the page after a number of seconds.
<META http-equiv=”Refresh” content=”10; url=”newPage.html” />
Refer Q9 in Enterprise section for question How would you get the browser to request for an updated page in 10 seconds? Once you can have the browser poll your Servlet on a regular basis to re-fetch a page, then your servlet can check for a value of a variable say in a HttpSession to determine if the page returned will have the results expected by the user or resend the <META> tag with a “Please wait …” message and retry fetching the page again later.
Solution 2: J2EE Solution: Instead of spawning your own threads within your Servlet, you could use JMS (Java Messaging Service). This involves following steps:
1.You need to have two servlets, a RequestingServlet and a DisplayingServlet. The initial client request is sent to the RequestingServlet. Both the RequestingServlet and DisplayingServlet polled by the browser via <META> tag discussed above or JavaScript. Both these Servlets should send the <META> tag with their responses until final display of the query results.
2.RequestingServlet places the query on the “request” queue using JMS.
3.You need to have a MessageDrivenBean (aka MDB) say QueryProcessorMDB, which dequeues the query from the “request” queue and performs the long-running database operation. On completion of processing long-running database operation, the QueryProcessorMDB returns the query results to the “reply” queue (use javax.jms.QueueSender & javax.jms.ObjectMessage). Note: MDBs are invoked asynchronously on arrival of messages in the queue.
4.DisplayingServlet checks the “reply” queue for the query results using JMS (use javax.jms.QueueReceiver & javax.jms.ObjectMessage) every few seconds via <META> tag described above or a JavaScript.
Advantages: Firstly implementing your long-running database operation to be invoked from onMessage() method of your QueryProcessorMDB decouples your application whereby if a database failure occurs, the request query message will be placed back in the “request” queue and retried again later. Secondly MDBs can be clustered (with or without additional JVMs) to listen on the same “request” queue. This means cluster of MDBs will be balancing the load of processing long running database operations. This can improve the throughput due to increased processing power.