Monday, June 29, 2009

JDBC Interview Questions


1) What is JDBC?
  • JDBC stands for Java Database Connectivity. It is an API which provides easy connection to a wide range of databases.

2) How do you connect to a database?
  • To connect to a database we need to load the appropriate driver and then request for a connectionobject.
  • The Class.forName(….) will load the driver and register it with the DriverManager.
  • Class.forName(“oracle.jdbc.driver.OracleDriver”); //dynamic class loading
  • String url = jdbc:oracle:thin:@hostname:1526:myDB;
  • Connection myConnection = DriverManager.getConnection(url, “username”, “password”);

3) What is JDBC Driver ?
  • The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API.
  • This driver is used to connect to the database.
  • Class.forName(“oracle.jdbc.driver.OracleDriver”);

4) What are the steps required to execute a query in JDBC?
  • First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to register this driver with DriverManager class.
  • Class.forName(“oracle.jdbc.driver.OracleDriver”);
  • Then we can open a connection.
  • Connection con = DriverManager.getConnection( "jdbc:myDriver:wombat", "myLogin","myPassword");
  • By using this connection , we can create a statement object and this object will help us to execute the query.
  • Statement stmt = con.createStatement();
  • ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");

5) What is DriverManager ?
  • DriverManager is a class in java.sql package.
  • It defines objects, which can connect Java applications to a JDBC driver.

6) What does Class.forName return?
  • A class as loaded by the classloader.

7) What is Connection?
  • Connection class represents a connection (session) with a specific database.
  • Connection con = DriverManager.getConnection( "jdbc:myDriver:wombat", "myLogin","myPassword");
  • SQL statements are executed and results are returned within the context of a connection.
  • Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on.
  • This information is obtained with the getMetaData method.

8) What is a ResultSet ?
  • A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
  • ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
  • A ResultSet object maintains a cursor pointing to its current row of data.
  • Initially the cursor is positioned before the first row.
  • The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}


9) What are JDBC Statements?
  • A statement object is responsible for sending the SQL statements to the Database.
  • Statement objects are created from the connection object and then executed.
  • Statement stmt = myConnection.createStatement();
  • ResultSet rs = stmt.executeQuery(“SELECT id, name FROM myTable where id =1245”);
  • stmt.executeUpdate(“INSERT INTO (field1,field2) values (1,3)”);//to insert/update/delete/create

10) What are different types of statements? How can you create them?
  • The types of statements are:
  • Statement (regular statement as shown above)
  • PreparedStatement (more efficient than statement due to pre-compilation of SQL)
  • PreparedStatement prepStmt = myConnection.prepareStatement("SELECT id, name FROM myTable where id = ? ");
  • prepStmt.setInt(1, 1245);
  • CallableStatement (to call stored procedures on the database)
  • CallableStatement calStmt = myConnection.prepareCall("{call PROC_SHOWMYBOOKS}");
  • ResultSet rs = cs.executeQuery();

11) What is a Transaction?
  • A transaction is a set of operations that should be completed as a unit. If one operation fails then all the other operations fail as well.
  • For example if you transfer funds between two accounts there will be two operations in the set1. Withdraw money from one account.2. Deposit money into other account.
  • There are four characteristics (ACID properties) for a Transaction.Atomicity (All the individual operations should either complete or fail.)Consistency (The design of the transaction should update the database correctly.)Isolation (Prevents data being corrupted by concurrent access by two different sources. It keepstransactions isolated or separated from each other until they are finished.)Durability(Ensures that the database is definitely updated once the Transaction is completed.)

12) What does setAutoCommit do?
  • When a connection is created, it is in auto-commit mode.
  • This means that each individual SQL statement is treated as a transaction and will be automatically committed immediately after it is executed.
  • The wayto allow two or more statements to be grouped into a transaction is to disable auto-commit.
modetry{
Connection myConnection = dataSource.getConnection();// set autoCommit to false
myConnection.setAutoCommit(false);
withdrawMoneyFromFirstAccount(.............); //operation 1
depositMoneyIntoSecondAccount(.............); //operation 2
myConnection .commit();
}
catch(Exception sqle){
try{
myConnection .rollback();
}catch( Exception e){}
}
finally{
try{
if( conn != null) {
conn.close();
}
} catch( Exception e) {}
}
The above code ensures that both operation 1 and operation 2 succeed or fail as an atomic unit and consequently leaves the database in a consistent state. Also turning auto-commit off will provide better performance.


13) What are stored procedures?
  • A stored procedure is a set of statements/commands which reside in the database.  The stored procedure is precompiled.
  • Each Database has it's own stored procedure language.

14) What is Connection pooling?
  • Connection pooling is a technique used for sharing server resources among requesting clients.
  • Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request.
  • Connection pool manager maintains a pool of open database connections.

15) Have you used a Data Access Object (i.e. DAO) pattern?
  • The DataSource interface provides an alternative to the DriverManager for making a connection.
  • DataSource makes the code more portable than DriverManager because it works with JNDI and it is created, deployed and managed separately from the application that uses it.
  • If the DataSource location changes, then there is no need to change the code but change the configuration properties in the server. This makes your application code easier to maintain.
  • DataSource allows the use of connection pooling and support for distributed transactions.
  • A DataSource is not only a database but also can be a file or a spreadsheet.
  • A DataSource object can be bound to JNDI and an application can retrieve and use it to make a connection to the database.
  • J2EE application servers provide tools to define your DataSource with a JNDI name. When the server starts it loads all the DataSources into the application server’s JNDI service.
  • DataSource configuration properties are shown below:JNDI Name -> jdbc/myDataSourceURL -> jdbc:oracle:thin:@hostname:1526:myDBUserName, PasswordImplementation classname ->oracle.jdbc.pool.OracleConnectionPoolDataSourceClasspath -> ora_jdbc.jarConnection pooling settings like ->minimum pool size, maximum pool size, connection timeout, statement cache size etc.
  • Once the DataSource has been set up, then you can get the connection object as follows:
  • Context ctx = new InitialContext();DataSource ds = (DataSource)ctx.lookup("jdbc/myDataSource");
  • Connection myConnection = ds.getConnection(“username”,”password”);

16) Why should you prefer using DataSource?
  • In a basic implementation a Connection obtained from a DataSource and a DriverManager are identical.
  • But the J2EE best practice is to use DataSource because of its portability, better performance due topooling of valuable resources and the J2EE standard requires that applications use the container’s resource management facilities to obtain connections to resources.
  • Every major web application container provides pooled database connection management as part of its resource management framework.

17) What are the different JDBC drivers available?There are mainly four type of JDBC drivers available.
They are:
Type 1 : JDBC-ODBC Bridge Driver - A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun.

Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.

Type 4: JDBC Net pure Java Driver - A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.


18) What is the fastest type of JDBC driver
  • Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).

19) Is the JDBC-ODBC Bridge multi-threaded?
  • No. The JDBC-ODBC Bridge does not support multi threading. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading.


20) What is cold backup, hot backup, warm backup recovery?
  • Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is 'online backup' ) is a backup taken of each tablespace while the database is running and is being accessed by the users

21) What is the advantage of denormalization?
  • Data denormalization is reverse procedure, carried out purely for reasons of improving performance.
  • It maybe efficient for a high-throughput system to replicate data for certain data.

22) How do you handle your own transaction ?
  • Connection Object has a method called setAutocommit ( boolean flag) . For handling our own transaction we can set the parameter to false and begin your transaction . Finally commit the transaction by calling the commit method.

References:
  1. Java/J2EE Job Interview Companion by Arulkumaran.
  2. http://www.allapplabs.com/index.html
  3. http://www.java-interview.com/index.html

JSP Interview Questions

1) What is JSP? Describe its concept
  • JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client.

2) What is client-side vs. server-side validation?
client-side validation (client-tier)
  • Java Script is used for client-side validation.
  • Validation takes place in client-side within your browser.
  • Java Script can be used to submit your form data after successful validation.
  • No extra network trip is required when there are validation errors because form does not have to be submitted.
server-side validation (presentation-tier)
  • Form data is submitted to the server and validation is carried out in the server.
  • Extra network round trip is required when there arevalidation errors because validation errors need to be reported back to the client and the form data has to be resubmitted.

3) What is JSP translation phase or compilation phase?
  • JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file into a JSP Servlet.
  • The translated and compiled JSP Servlet moves to the execution phase (run time) where they can handle requests and send responses.
  • The JSPs can be compiled ahead of time (i.e. precompiled) using application server tools/settings or by writing our own script.

4) Explain the life cycle methods of a JSP?
  • Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
  • Translated: The JSP file has been translated and compiled as a Servlet.
  • Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance.
  • Servicing: Services the client requests. Container calls the _jspService() method for each request.
  • Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.

5) What are context initialization parameters
  • Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

6) What is an output comment
  • A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser. JSP Syntax


7) What is a Hidden Comment
  • A comment that documents the JSP page but is not sent to the client.
  • The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags.
  • JSP Syntax

8) What is an Expression
  • An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
  • Because the value of an expression is converted to a String, you can use an expression within text in a JSP file.
  • LikeYou cannot use a semicolon to end an expression

9) What is a Declaration
  • It declares one or more variables or methods for use later in the JSP source file.
  • A declaration must contain at least one complete declarative statement.
  • You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them.
  • The declaration must be valid in the scripting language used in the JSP file.

10) What is a Scriptlet
  • A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.
  • Within scriptlet tags, you can declare variables or methods to use later in the file, write expressions valid in the page scripting language.
  • Use any of the JSP implicit objects or any object declared with a tag.
  • You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
  • Scriptlets are executed at request time, when the JSP engine processes the client request.
  • If the scriptlet produces output, the output is stored in the out object, from which you can display it.

11) What are the implicit objects
  • Certain objects that are available for the use in JSP documents without being declared first.
  • These objects are parsed by the JSP engine and inserted into the generated servlet.
  • The implicit objects are:
  • request response pageContext session application out config page exception

12) What is the difference between forward and sendRedirect
  • When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request.
  • This process occurs completely with in the web container And then returns to the calling method.
  • When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested.
  • Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

13) What are the different scope values
  • The different scope values for are:page request session application

14) Why are JSP pages the preferred API for creating a web-based client program
  • Because no plug-ins or security policy files are needed on the client systems(applet does).
  • Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design.
  • This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

15) Is JSP technology extensible
  • Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

16) What is difference between custom JSP tags and beans
  • Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files.
  • Custom tags and beans accomplish the same goals of encapsulating complex behavior into simple and accessible forms.
  • There are several differences:
  • Custom tags can manipulate JSP content; beans cannot.
  • Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
  • Custom tags require quite a bit more work to set up than do beans.  Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
  • Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

17) How does JSP handle run-time exceptions
  • You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
  • For example: redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.
  • Within error.jsp, if you indicate that it is an error-processing page, via the directive: Throwable object describing the exception may be accessed within the error page via the exception implicit object.
  • Note: You must always use a relative URL as the value for the errorPage attribute.

18) What is the difference between ServletContext and PageContext
ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request.


19) What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()
  • request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource,
  • context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

20) How to pass information from JSP to included JSP
  • Using The is used for including non-JSP files.

23) What is the difference between directive include and jsp include
  • <%@ include>: Used to include static resources during translation time.
  • JSP include: Used to include dynamic content or static content during runtime.

References:
  1. Java/J2EE Job Interview Companion by Arulkumaran.
  2. http://www.allapplabs.com/index.html
  3. http://www.java-interview.com/index.html
  4. Headfirst Servlet and Jsp by Bryan Basham, Kathy Sierra, Bert Bates




Thursday, June 18, 2009

Servlet Interview Questions

1) What is the difference between CGI and Servlet?

Traditional CGI(Common Gateway Interface)
  • Traditional CGI creates a heavy weight process to handle each http request.
  • N number of copies of the same traditional CGI programs is copied into memory to serve N number of requests.
Servlet
  • Java ServletServlets a lightweight Java thread to handle each http request.
  • Single copy of a type of servlet but N number of threads (thread sizes can be configured in an application server).


2) What is a Servlet?
  • A Servlet is a Java class that runs within a web container in an application server, servicing multiple client requests.

3) What are the two objects a servlet receives when it accepts a call from its client?
  • A “ServletRequest”, which encapsulates client request from the client.
  • A “ServletResponse”, which encapsulates the communication from the servlet back to the client.

4) Explain the life cycle methods of a servlet?
  • The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
  • public void init(ServletConfig config) throws ServletException
  • public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
  • public void destroy()
  • The Web container is responsible for managing the servlet’s life cycle.
  • The Web container creates an instance of the servlet and then the container calls the init() method.
  • At the completion of the init() method the servlet is in ready state to service requests from clients.
  • The container calls the servlet’s service() method for handling each request.
  • Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.

5) What is preinitialization of a servlet?
  • The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
  • The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.
  • A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called ***lazy loading***.

6) What is the difference between HttpServlet and GenericServlet?
  • Both these classes are abstract but:
GenericServlet
  • A GenericServlet has a service() method to handle 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.
HttpServlet
  • The HttpServlet extends GenericServlet and adds support for HTTP protocol based methods like doGet(), doPost(), doHead() etc.
  • HttpServlet also has methods like doHead(), doPut(), doOptions(), doDelete(), and doTrace().Protocol independent. GenericServlet is for servletsthat might not use HTTP (for example FTP service). Protocol dependent

7) Explain ServletContext.
  • A servlet can use ServletContext interface to get information such as initialization parameters for the web application.
  • Every web application has one and only one ServletContext and is accessible to all active resource of that application.

8) What are the ServletContext and ServletConfig objects? What are Servlet environment objects?
ServletConfig
  • 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.
  • The ServletConfig parameters are for a particularServlet.
  • The parameters are specified in the web.xml(i.e. deployment descriptor). It is created after a servlet is instantiated and it is used to pass initialization information to the servlet.
ServletContext
  • The ServletContext parameters are specified for the entire Web application.
  • The parameters are specified in the web.xml (i.e. deployment descriptor).
  • Servlet context is common to all Servlets. So all Servlets share information through ServletContext.

9) 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.

10) 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.


11)What is the difference between doGet () and doPost () or GET and POST?

GET or doGet()
  • The request parameters are transmitted as a query string appended to the request. All the parameters get appended to the URL in the address bar. Allows browser bookmarks but not appropriate for transmitting private or sensitive information.
  • http://MyServer/MyServlet?name=paul This is a security risk.
  • GET is not appropriate when large amounts of input data are being transferred. Limited to 1024 characters.
POST or doPost()
  • The request parameters are passed with the body of the request. More secured.
  • In HTML you can specify as follows:
  • POST was intended for form submits where the state of the model and database are expected to change.
  • Since it sends information through a socket back to the 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.

12) HTTP is a stateless protocol, so, how do you maintain state? How do you store user data between requests?
  • 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. In a Java servlet the session can be obtained as follows:
  • 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 basissession.setMaxInactiveInterval(300);//resets inactivity period for this session as 5 minutes

13) What is the difference between using getSession(true) and getSession(false) methods?
getSession(true): This method will check whether there is already a session exists for the user. If a sessionexists, it returns that session object. If a session does not already exist then it creates a new session for the user.

getSession(false): This method will check whether there is already a session exists for the user. If a sessionexists, it returns that session object. If a session does not already exist then it returns null.


14) What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
  • The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet.
  • If the path begins with a "/" it is interpreted as relative to the current context root.
  • The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths.
  • All path must start with a "/" and are interpreted as relative to current context root.

15) What is the difference between forwarding a request and redirecting a request? Both methods send you to a new resource like Servlet, JSP etc.
redirecting - sendRedirect()
  • Sends a header back to the browser, which contains the name of the resource to be redirected to. The browser will make a fresh request from this header information. Need to provide absolute URL path.
Forward
  • Forward action takes place within the server withoutthe knowledge of the browser. Accepts relative path to the servlet or context root.Has an overhead of extra remote trip but has the advantage of being able to refer to any resource on the same or different domain and also allows book marking of the page. No extra network trip.

16) Explain the directory structure of a web application.
  • The directory structure of a web application consists of two parts.
  • A private directory called WEB-INFA public resource directory which contains public resource folder.
  • WEB-INF folder consists of web.xml classes directory lib directory

17) What is a filter, and how does it work?
  • A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses but typically do not themselves create responses.
  • Filters can also be used to transform the response from the Servlet or JSP before sending it back to client. Filters improve reusability by placing recurring tasks in the filter as a reusable unit.


18) How do you make a Servlet thread safe? What do you need to be concerned about with storing data in Servlet instance fields?
  • A Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method.
  • The multithreading aids efficiency but the servlet code must be coded in a thread safe manner.
  • The shared resources (e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner.
  • There are situations where synchronizing will not give you the expected results and to achieve the expected results you should store your values in a user session or store them as a hidden field values.
  • Having large chunks of code in synchronized blocks in your service or doPost() methods can adversely affect performance and makes the code more complex.Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or nullinterface 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 randomly 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.

19) 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-byvalue”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) 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.

References:
  1. Java/J2EE Job Interview Companion by Arulkumaran.
  2. http://www.allapplabs.com/index.html
  3. http://www.java-interview.com/index.html