Tuesday, November 1, 2011

Servlet interview questions with answers

What is the servlet?
Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.
-Servlets are used to enhance and extend the functionality of Webserver.
Servlets handles Java and HTML separately.

What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task.

What are the characters of Servlet?
As Servlet are written in java, they can make use of extensive power of the JAVA API,such as networking and URL access,multithreading,databaseconnectivity,RMI object serialization.
Efficient : The initilazation code for a servlet is executed only once, when the servlet is executed for the first time.
Robest : provide all the powerfull features of JAVA, such as Exception handling and garbage collection.
Portable: This enables easy portability across Web Servers.
Persistance : Increase the performance of the system by executing features data access.

What is the difference between JSP and SERVLETS
Servlets : servlet tieup files to independitently handle the static presentation logic and dynamic business logic , due to this a changes made to any file requires recompilation of the servlet.
- The servlet is Pre-Compile.

JSP : Facilities segregation of work profiles to Web-Developer and Web-Designer , Automatically incorporates changes made to any file (PL & BL) , no need to recompile.
Web-Developer write the code for Bussiness logic whereas Web-Designer designs the layout for the WebPage by HTML & JSP.
- The JSP is Post-Compile.

What are the advantages using servlets than using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs. They are developed with Java Servlet API, a standard Java extension.

What is the difference between servlets and applets?
Servlets are to servers. Applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

What is the difference between GenericServlet and HttpServlet?
GenericServlet is for servlets that might not use HTTP, like for instance FTP service.As of only Http is implemented completely in HttpServlet. The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are.
GenericServlet belongs to javax.servlet package
GenericServlet is an abstract class which extends Object and implements Servlet, ServletConfig and java.io.Serializable interfaces.
The direct subclass to GenericServlet is HttpServlet.It is a protocol-independent servlet

What are the differences between GET and POST service methods?
Get Method : Uses Query String to send additional information to the server.
-Query String is displayed on the client Browser.
Query String : The additional sequence of characters that are appended to the URL ia called Query String. The length of the Query string is limited to 255 characters.
-The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.

POST Method : The Post Method sends the Data as packets through a separate socket connection. The complete transaction is invisible to the client. The post method is slower compared to the Get method because Data is sent to the server as separate packates.
--You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
What is the servlet life cycle?
In Servlet life cycles are,
init(),services(),destory().
Init( ) : Is called by the Servlet container after the servlet has ben Instantiated.
--Contains all information code for servlet and is invoked when the servlet is first loaded.
-The init( ) does not require any argument , returns a void and throws Servlet Exception.
-If init() executed at the time of servlet class loading.And init() executed only for first user.
-You can Override this method to write initialization code that needs to run only once, such as loading a driver , initializing values and soon, Inother case you can leave normally blank.
Public void init(ServletConfig Config) throws ServletException

Service( ) : is called by the Servlet container after the init method to allow the servlet to respond to a request.
-Receives the request from the client and identifies the type of request and deligates them to doGet( ) or doPost( ) for processing.
Public void service(ServletRequest request,ServletResponce response) throws ServletException, IOException

Destroy( ) : The Servlet Container calls the destroy( ) before removing a Servlet Instance from Sevice.
-Excutes only once when the Servlet is removed from Server.
Public void destroy( )

If services() are both for get and post methods.
-So if u want to use post method in html page,we use doPost() or services() in servlet class.
-if want to use get methods in html page,we can use doGet() or services() in servlet calss.
-Finally destory() is used to free the object.

What is the difference between ServletContext and ServletConfig?
Both are interfaces.
Servlet Config():The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.
A ServletConfig object passes configuration information from the server to a servlet. ServletConfig also includes ServletContext object.
getParameter( ) , getServletContext( ) , getServletConfig( ), GetServletName( )

Servlet Context(): The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.
ServletContext defines methods that allow a servlet to interact with the host server. This includes reading server-specific attributes, finding information about particular files located on the server, and writing to the server log files. I f there are several virtual servers running, each one may return a different ServletContext.
getMIMEType( ) , getResourse( ), getContext( ),getServerInfo( ),getServletContetName( )
11. Can I invoke a JSP error page from a servlet?
Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets.

Can I just abort processing a JSP?
Yes.Because your JSP is just a servlet method,you can just put (whereever necessary) a < % return; %>

What is a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

If you want a servlet to take the same action for both GET and POST request, what should you do?
Simply have doGet call doPost, or vice versa.

Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set before transmitting the actual document.

How HTTP Servlet handles client requests?
An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

What is the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.
Servlets-->Generic Servlet-->HttpServlet-->MyServlet.
The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

When a servlet accepts a call from a client, it receives two objects. What are they?
ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the
Client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

What information that the ServletRequest interface allows the servlet access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data
from clients that use application protocols such as the HTTP POST and PUT methods.

What information that the ServletResponse interface gives the servlet methods for replying to the client?
It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

Difference between single thread and multi thread model servlet
A servlet that implements SingleThreadModel means that for every request, a single servlet instance is created. This is not a very scalable solution as most web servers handle multitudes of requests. A multi-threaded servlet means that one servlet is capable of handling many requests which is the way most servlets should be implemented.
a. A single thread model for servlets is generally used to protect sensitive data ( bank account operations ).
b. Single thread model means instance of the servlet gets created for each request recieved. Its not thread safe whereas in multi threaded only single instance of the servlet exists for what ever # of requests recieved. Its thread safe and is taken care by the servlet container.
c. A servlet that implements SingleThreadModel means that for every request, a single servlet instance is created. This is not a very scalable solution as most web servers handle multitudes of requests. A multi-threaded servlet means that one servlet is capable of handling many requests which is the way most servlets should be implemented.

A single thread model for servlets is generally used to protect sensitive data ( bank account operations ).

What is servlet context and what it takes actually as parameters?
Servlet context is an object which is created as soon as the Servlet gets initialized.Servlet context object is contained in Servlet Config. With the context object u can get access to specific
resource (like file) in the server and pass it as a URL to be displayed as a next screen with the help of RequestDispatcher
eg :-
ServletContext app = getServletContext();
RequestDispatcher disp;
if(b==true)
disp = app.getRequestDispatcher
("jsp/login/updatepassword.jsp");
else
disp = app.getRequestDispatcher
("jsp/login/error.jsp");
this code will take user to the screen depending upon the value of b.
in ServletContext u can also get or set some variables which u would
like to retreive in next screen.
eg
context.setAttribute("supportAddress", "temp@temp.com");
Better yet, you could use the web.xml context-param element to
designate the address, then read it with the getInitParameter method
of ServletContext.

Can we call destroy() method on servlets from service method?
destroy() is a servlet life-cycle method called by servlet container to kill the instance of the servlet. "Yes". You can call destroy() from within the service(). It will do whatever logic you have in destroy() (cleanup, remove attributes, etc.) but it won't "unload" the servlet instance itself. That can only be done by the container
What is the use of ServletConfig and ServletContext..?
An interface that describes the configuration parameters for a servlet. This is passed to the servlet when the web server calls its init() method. Note that the servlet should save the reference to the ServletConfig object, and define a getServletConfig() method to return it when asked. This interface defines how to get the initialization parameters for the servlet and the context under which the servlet is running.
An interface that describes how a servlet can get information about the server in which it is running. It can be retrieved via the getServletContext() method of the ServletConfig object.

What is difference between forward() and sendRedirect().. ? Which one is faster then other and which works on server?
Forward( ) : javax.Servlet.RequestDispatcher interface.
-RequestDispatcher.forward( ) works on the Server.
-The forward( ) works inside the WebContainer.
-The forward( ) restricts you to redirect only to a resource in the same web-Application.
-After executing the forward( ), the control will return back to the same method from where the forward method was called.
-the forward( ) will redirect in the application server itself, it does’n come back to the client.
- The forward( ) is faster than Sendredirect( ) .
To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain RequestDispatcher Object. The Servlet technology provides in three ways.
1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a String containing the path of the other resources, path is relative to the root of the ServletContext.

RequestDispatcher rd=request.getRequestDispatcher(“secondServlet”);
Rd.forward(request, response);

2. getRequestDispatcher( ) of the javax.Servlet.Request interface , the path is relative to current HtpRequest.
RequestDispatcher rd=getServletContext( ).getRequestDispatcher(“servlet/secondServlet”);
Rd.forward(request, response);

3. By using the getNameDispatcher( ) of the javax.Servlet.ServletContext interface.
RequestDispatcher rd=getServletContext( ).getNameDispatcher(“secondServlet”);
Rd.forward(request, response);

Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface
-RequestDispatcher.SendRedirect( ) works on the browser.
-The SendRedirect( ) allows you to redirect trip to the Client.
-The SendRedirect( ) allows you to redirect to any URL.
-After executing the SendRedirect( ) the control will not return back to same method.
-The Client receives the Http response code 302 indicating that temporarly the client is being redirected to the specified location , if the specified location is relative , this method converts it into an absolute URL before redirecting.

-The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen.
Response. SendRedirect( “absolute path”);
Absolutepath – other than application , relative path - same application.

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. When a sendRedirtect 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.

do we have a constructor in servlet ? can we explictly provide a constructor in servlet programme as in java program ?
We can have a constructor in servlet .

Session : A session is a group of activities that are performed by a user while accesing a particular website.
Session Tracking :The process of keeping track of settings across session is called session tracking.
Hidden Form Fields : Used to keep track of users by placing hidden fields in the form.
-The values that have been entered in these fields are sent to the server when the user submits the Form.
URL-rewriting : this is a technique by which the URL is modified to include the session ID of a particular user and is sent back to the Client.
-The session Id is used by the client for subsequent transactions with the server.
Cookies : Cookies are small text files that are used by a webserver to keep track the Users.
A cookie is created by the server and send back to the client , the value is in the form of Key-value pairs. Aclient can accept 20 cookies per host and the size of each cookie can be maximum of 4 bytes each.
HttpSession : Every user who logs on to the website is autometacally associated with an HttpSession Object.
-The Servlet can use this Object to store information about the users Session.
-HttpSession Object enables the user to maintain two types of Data.
ie State and Application.

How to communicate between two servlets?
Two ways:
a. Forward or redirect from one Servlet to another.
b. Load the Servlet from ServletContext and access methods.
29. How to get one Servlet's Context Information in another Servlet?
Access or load the Servlet from the Servlet Context and access the Context Information

Tuesday, October 18, 2011

JDBC FAQS

What is JDBC?
Ans: JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to Java Database applications. The database vendors like Oracle,MySql ,TeraData ….are provided the implementations for some of the classes in JDBC API.

What are drivers available?
Ans: Type 1- JDBC-ODBC Bridge driver
Type 2- Native API Partly-Java driver
Type 3 -JDBC-Net Pure Java driver
Type 4 -Native-Protocol Pure Java driver

What is the difference between JDBC and ODBC?
Ans: a) ODBC(Open Data Base Connectivity) is for Microsoft and JDBC is for Java applications.
b) ODBC can’t be directly used with Java because it uses a C interface.
c) ODBC makes use of pointers which have been removed totally from Java.
d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required.
e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms.
f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.

What are the types of JDBC Driver Models and explain them?
Ans: There are two types of JDBC Driver Models and they are:
a) Two tier model and b) Three tier model
Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server.
Three tier model: A middle tier is introduced in this model. The functions of this model are:
a) Collection of SQL statements from the client and handing it over to the database,
b) Receiving results from database to the client and
c) Maintaining control over accessing and updation of the above.

What are the steps involved for making a connection with a database or how do you connect to a database?
Ans:
a) Loading the driver : To load the driver, Class.forName( ) method is used.
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
When the driver is loaded, it registers itself with the java.sql.DriverManager class as an available database driver.
b) Making a connection with database : To open a connection to a given database,
DriverMnaager.getConnection( ) method is used.
Connection con = DriverManager.getConnection(“jdbc:odbc:somedb”, “user”, ”password”);
c) Executing SQL statements : To execute a SQL query, java.sql.statements class is used.
createStatement( ) method of Connection to obtain a new Statement object.
Statement stmt = con.createStatement( );
A query that returns data can be executed using the executeQuery( ) method of Statement. This method
executes the statement and returns a java.sql.ResultSet that encapsulates the retrieved data:
ResultSet rs = stmt.executeQuery(“SELECT * FROM some table”);
d) Process the results : ResultSet returns one row at a time. Next( ) method of ResultSet object can be called to move to the next row. The getString( ) and getObject( ) methods are used for retrieving column values:
while(rs.next( ) ) {
String event = rs.getString(“event”);
Object count = (Integer) rs.getObject(“count”);

What type of driver did you use in project?
Ans: JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).

What are the types of statements in JDBC?
Ans: Statement -- To be used createStatement( ) method for executing single SQL statement
PreparedStatement -- To be used preparStatement( ) method for executing same SQL statement over and over.
CallableStatement -- To be used prepareCall( ) method for multiple SQL statements over and over

What is stored procedure?
Ans: Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.

How to create and call stored procedures?
Ans: To create stored procedures:
Create procedure procedure name (specify in, out and in out parameters)
BEGIN
Any multiple SQL statement;
END;

To call stored procedures:
CallableStatement csmt = con.prepareCall(“{call procedure name(?,?)}”);
csmt.registerOutParameter(column no., data type);
csmt.setInt(column no., column name)
csmt.execute( );

What are the differences between executeQuery(…), executeUpdate(…) and execute(…) methods?
Ans:
public ResultSet executeQuery(String sqlquery)

where executeQuery() can be used to execute selection group sql queries to fetch the data from database.When we use selection group sql query with executeQuery() then JVM will send that sql query to the database engine, database engine will execute it, by this database engine(DBE) will fetch the data from database and send back to the java application.

public int executeUpdate(String sqlquery)

where executeUpdate() can be used to execute updation group sql query to update the database. When we provide updation group sql query as a parameter to executeUpdate(), then JVM will send that sql query to DBE, here DBE will execute it and perform updations on the database, by this DBE will identify the number of records got updated value called as “records updated count” and return back to the java application.

public boolean execute(String sqlquery)

where execute() can be used to execute either selection group sql queries or updation group queries. But this method is renturn value is Boolean to get the ResultSet object to call the statement.get ResultSet() method . If we want to get Update count we have to use the statement.getUpdateCount() method.


What is a transaction ?
transaction is collection of logical operation that perform a task
Transaction should ACID properties.
A for Automicity
C for Consistency
I for Isolation
D for Durability.
A transaction can be termed as any operation such as storing, retrieving, updating or deleting records in the table that hits the database.

What is the purpose of setAutoCommit( )
It is set as ConnectionObject.setAutoComit(boolean val);
after any updates through the program cannot be effected to the database.We have to commit the transctions then only it reflect on Database .For this puprpose we can set AutoCommit flag to Connection Object.