Servlet Java Interview Questions | Eklavya Online

Servlet Java Interview Questions

  • JSP files,
  • class files for servlets,
  • GIF and HTML files, and
  • a Web deployment descriptor.

Web modules are packaged as JAR files with a .war (Web ARchive) extension.

Here is the sample code that makes use of the default compareTo( ) provided in the String class as it implements the Comparable interface and the Collections utility class that provides a sorting method, which internally uses the efficient “merge sort” algorithm.

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

 

public class Sort1 {

public static void main(String[] args) {

List<string> values = Arrays.asList(“JEE”, “Java”, “Servlets”, “JMS”, “JNDI”, “JDBC”, “JSP”, “EJB”);

Collections.sort(values); // uses the default compareTo(String anotherString)  in the String class

System.out.println(values);

}

}

Output:

[EJB, JDBC, JEE, JMS, JNDI, JSP, Java, Servlets]

There are no structural differences between the files; they are all archived using zip-jar compression.

However, they are intended for different purposes.

  • Jar files (files with a .jar extension) arre intended to hold generic libraries of Java classes, resources, auxiliary files, etc.
  • War files (files with a .war extension) arre intended to contain complete Web applications. In this context, a Web application is defined as a single group of files, classes, resources, .jar files that can be packaged and accessed as one servlet context.
  • Ear files (files with a .ear extension) arre intended to contain complete enterprise applications. In this context, an enterprise application is defined as a collection of .jar files, resources, classes, and multiple Web applications.

Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc.

Yes, 2 things — firstly, the above sort is case sensitive, that is the uppercase takes priority over lowercase pushing ‘Java’ after ‘JSP’. Secondly, if the collection had any null values, it will throw a NullpointerException.

These two issues can be rectified by providing a custom sorting implementation that ignores case and handles null values by pushing them to the end. The Collections class’s sort method takes a Comparator implementation as a second argument. In the code below, the Comparator has been implemented as an anonymous inner class. The compare(…) method will be called a number of times by the Collections.sort(list, comparator).

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

 

public class Sort2 {

 

public static void main(String[] args) {

List<String> values = Arrays.asList(“JEE”, “Java”, null,  “Servlets”, null, “JMS”, “JNDI”, “JDBC”, “JSP”, null,”EJB”);

 

//The comparator is defined as an anonymous inner class, but it can be

//defined in its own class. Handles nulls and ignores case

Collections.sort(values, new Comparator<String>() {

 

@Override

public int compare(String o1, String o2) {

//push the null values to the end

if(o1 == null){

if(o2 == null) {

return 0;

}

return 1;

}

else if(o2 == null){

return -1;

}

return o1.compareToIgnoreCase(o2);

}

}); // anonymous inner class end

 

System.out.println(values);

}

}

The process that verifies the identity of a user, device, or other entity in a computer system, usually as a prerequisite to allowing access to resources in a system. The Java servlet specification requires three types of authentication-basic, form-based, and mutual-and supports digest authentication.

Any number of Comparator classes can be created to sort them differently as shown below.

import java.util.Comparator;

 

public class JavaTechnologyComparator implements Comparator<JavaTechnology> {

 

@Override

public int compare(JavaTechnology t1, JavaTechnology t2) {

 

//handle null values here

Integer rank1 = t1.getRank();

Integer rank2 = t2.getRank();

int rankVal = rank1.compareTo(rank2);

int nameVal = t1.getName().toLowerCase().compareTo(t2.getName().toLowerCase());

 

//if same rank, then sort by name

if(rankVal == 0){

return nameVal;

}

//else sort by rank

return rankVal ;

}

}

Now, the Sort3Test class has been slightly modified to use a Comparator.

import java.util.Collections;

import java.util.List;

 

public class Sort3Test {

public static void main(String[] args) {

 

JavaTechnology jt1 = new JavaTechnology(“JEE”, 1);

JavaTechnology jt2 = new JavaTechnology(“Java”, 1);

JavaTechnology jt3 = new JavaTechnology(“Servlets”, 2);

JavaTechnology jt4 = new JavaTechnology(“JSP”, 2);

JavaTechnology jt5 = new JavaTechnology(“JNDI”, 3);

JavaTechnology jt6 = new JavaTechnology(“EJB”, 4);

JavaTechnology jt7 = new JavaTechnology(“JMS”, 5);

 

List<JavaTechnology> values = Arrays.asList(jt1, jt2, jt3, jt4, jt5, jt6, jt7);

 

Collections.sort(values, new JavaTechnologyComparator());

// invokes the compare(…) in JavaTechnologyComparator

// a number of times

System.out.println(values);

}

}

The output will be:

[(Java , 1), (JEE , 1), (JSP , 2), (Servlets , 2), (JNDI , 3), (EJB , 4), (JMS , 5)]

This should now enable you to sort any Java objects.

Here is an example of a JavaTechnology custom object that implements a default sorting logic based on the rank (i.e popularity).

public class JavaTechnology implements Comparable<JavaTechnology>{

 

private String name;

private int rank;   // popularity lower value means more popular

 

public JavaTechnology(String name, int rank){

this.name = name;

this.rank = rank;

}

 

//default implementation by rank alone

@Override

public int compareTo(JavaTechnology technology) {

int rank1 = this.rank;

int rank2 = technology.rank;

if (rank1 > rank2){

return +1;

}else if (rank1 < rank2){

return -1;

}else{

return 0;

}

}

 

//required for printing, displaying, etc.

@Override

public String toString() {

return “(” + name + ” , ” + rank + “)”;

}

}

Now, a simple test class

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

 

public class Sort3Test {

 

public static void main(String[] args) {

JavaTechnology jt1 = new JavaTechnology(“JEE”, 1);

JavaTechnology jt2 = new JavaTechnology(“Java”, 1);

JavaTechnology jt3 = new JavaTechnology(“Servlets”, 2);

JavaTechnology jt4 = new JavaTechnology(“JSP”, 2);

JavaTechnology jt5 = new JavaTechnology(“JNDI”, 3);

JavaTechnology jt6 = new JavaTechnology(“EJB”, 4);

JavaTechnology jt7 = new JavaTechnology(“JMS”, 5);

 

List<javatechnology> values = Arrays.asList(jt1, jt2, jt3, jt4, jt5, jt6, jt7);

 

Collections.sort(values); // invokes the compareTo(…) method in JavaTechnology a number of times

 

System.out.println(values);

 

}

 

}

Output:

[(JEE , 1), (Java , 1), (Servlets , 2), (JSP , 2), (JNDI , 3), (EJB , 4), (JMS , 5)]

Both method calls redirect you to new resource/page/servlet. The difference between the two is that sendRedirect always sends a header back to the client/browser, containing the data in which you wanted to be redirected.

A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:

  • Application clients and applets are client components.
  • Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components.
  • Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
  • Resource adapter components provided by EIS and tool vendors.

The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

response. setHeader(”Set-Cookie”, “cookie string”); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) – to the bean, and in jsp-file:<% bean. setResponse (response); %>

JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology – you can’t do any client side validation with it. The advantages are: a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.

JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and well-defined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User Interface components for Web Applications.

Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication

To create stored procedures: Create procedure procedurename (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 is servlet?– Servlets are modules that extend request/response-oriented

JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms: a) Expressions of the form <%= expression %> that are evaluated and inserted into the output, b) Scriptlets of the form<% code %>that are inserted into the servlet’s service method, and c) Declarations of the form <%! Code %>that are inserted into the body of the servlet class, outside of any existing methods.

  1. a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic

Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database

JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.

A JSP directive affects the overall structure of the servlet class. It usually has the following form:<%@ directive attribute=”value” %> However, you can also combine multiple attribute settings for a single directive, as follows:<%@ directive attribute1=”value1″ attribute 2=”value2″ . . . attributeN =”valueN” %> There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet

With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid. A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not. A program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool.

?– The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies.

There are two packages in servlets and they are javax. servlet and

Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation – allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse – allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration – requires to communicate with each other by sharing specific information (through method invocation)

Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication – occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. b) Hidden form fields – fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server. c) URL rewriting – every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies – a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.

  1. a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include – Include a file at the time the page is requested. jsp:useBean – Find or instantiate a JavaBean. jsp:setProperty – Set the property of a JavaBean. jsp:getProperty – Insert the property of a JavaBean into the output. jsp:forward – Forward the requester to a newpage. Jsp: plugin – Generate browser-specific code that makes an OBJECT or EMBED

Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).

)?– Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.

The marker interface is a design pattern, used with languages that provide run-time type information about objects. It provides a way to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface, and code that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies methods that an implementing class must support, a marker interface does not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. There can be some hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. Java utilizes this pattern very well and the example interfaces are:

  • io.Serializable – Serializability of a class is enabled by the class implementing the java.io.Serializable interface. The Java Classes that do not implement Serializable interface will not be able to serialize or deserializ their state. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
  • rmi.Remote – The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a “remote interface”, an interface that extends java.rmi.Remote are available remotely.
  • lang.Cloneable – A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object’s clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
  • servlet.SingleThreadModel – Ensures that servlets handle only one request at a time. This interface has no methods.
  • util.EvenListener – A tagging interface that all event listener interfaces must extend.
  • The “instanceof” keyword in java can be used to test if an object is of a specified type. So this keyword in combination with Marker interface can be used to take different actions based on type of interface an object implements.

?– (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either “include” or forward”) can be called. This bean will disappear after processing this request has been completed. Servlet: request. setAttribute(”theBean”, myBean); RequestDispatcher rd = getServletContext(). getRequestDispatcher(”thepage. jsp”); rd. forward(request, response); JSP PAGE:<jsp: useBean id=”theBean” scope=”request” class=”. . . . . ” />(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it. Servlet: HttpSession session = request. getSession(true); session. putValue(”theBean”, myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */ JSP Page:<jsp:useBean id=”theBean” scope=”session” class=”. . . ” /> 3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it. Servlet: GetServletContext(). setAttribute(”theBean”, myBean); JSP PAGE:<jsp:useBean id=”theBean” scope=”application” class=”. . . ” />

Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.

Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().

Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client’s requests through service() method. c) The server removes the servlet through destroy() method.

If present, calls the servlet’s service() method at the specified times. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new Thread.

The value is a list of 24-hour times when the servlet should be automatically executed. To run the servlet every 6 hours, you could use:

<servlet servlet-name=”test.HelloWorld”>

<run-at>0:00, 6:00, 12:00, 18:00</run-at>

</servlet>

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

  • The servlet is initialized by calling the init ()
  • The servlet calls service()method to process a client’s request.
  • The servlet is terminated by calling the destroy()
  • Finally, servlet is garbage collected by the garbage collector of the JVM.

Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code, making JSPs more flexible and powerful than Servlets.

However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They have their strengths too which cannot be overseen.

JSP translation is an action that refers to the convertion of the JSP Page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.

Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. A servlet is a Java class implementing the javax.servlet.Servlet interface that runs within a Web or application server’s servlet engine, servicing client requests forwarded to it through the server. A Java Server Page is a slightly more complicated beast. JSP pages contain a mixture of HTML, Java scripts (not to be confused with JavaScript), JSP elements, and JSP directives. The elements in a Java Server Page will generally be compiled by the JSP engine into a servlet, but the JSP specification only requires that the JSP page execution entity follow the Servlet Protocol.

The advantage of Java Server Pages is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development. Rather than choosing between servlets and Java Server Pages, you will find that most non-trivial applications will want to use a combination of JSP and servlets. In fact, the JSP 1.1 and Servlet 2.2 specifications are based around the concept of the Web application, combining the two APIs into a unified framework.

Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.

  • ServletConfig a 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.

<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>

 

 

publicvoidinit()

{

ServletConfig config = getServletConfig();

String driverClassName = config.getInitParameter(“driverclassname”);

String dbURL = config.getInitParameter(“dburl”);

Class.forName(driverClassName);

dbConnection = DriverManager.getConnection(dbURL,username,password);

}

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException

{

// Initialization code…

}

Life-cycle methods of the JSP are:

  1. jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
  2. _jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann’t be overridden.
  3. jspDestroy(): The container calls this when its instance is about to destroyed.
    The jspInit() and jspDestroy() methods can be overridden within a JSP page.

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. To use custom JSP tags, you need to define three separate components:

  • the tag handler class that defines the tag\’s behavior
  • the tag library descriptor file that maps the XML element names to the tag implementations
  • the JSP file that uses the tag library

When the first two components are done, you can use the tag by using taglib directive:

<%@ taglib uri=”xxx.tld” prefix=”…” %>

Then you are ready to use the tags you defined. Let’s say the tag prefix is test:

MyJSPTag or

JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class.

<%=identifier.getclassField() %>

Custom tags and beans accomplish the same goals — 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.

A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet.

A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

Yes. However, unlike Servlet, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as.

Is there a way to reference the “this” variable within a JSP page? Yes, there is. Under JSP 1.0, the page implicit object is equivalent to “this”, and returns a reference to the Servlet generated by the JSP page.

  • Efficient: With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like.
  • Convenient: Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.
  • Powerful: Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can’t). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations.
  • Portable: Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server.
  • Inexpensive: There are a number of free or very inexpensive Web servers available that are good for “personal” use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn’t come preconfigured to support servlets) is generally free or cheap.
  • ServletContextInterface defines methods that a servlet can use to communicate to the Container.
  • ServletContext Parameters are specified for entire application and are available for all servlets.
  • ServletContext is also calledapplication 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.

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException

{

// code….

}

  • The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate.
  • So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
  • The doGet() and doPost() are most frequently used methods with in each service request. Here are the signature of these two methods.
  • Servlet is server side component, a servlet is small pluggable extension to the server.
  • Servlets are used to extend the functionality of the java-enabled server.
  • Servlets will be loaded in theAddress space of web server.
  • Servlet can be loaded in 3 ways
    • When the web sever starts.
    • You can set this in the configuration file.
    • Through an administration interface.
  • <%@ include file=”filename” %> is the JSP include directive.At JSP page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally JSP include directive is used to include header banners and footers.The JSP compilation procedure is that, the source JSP page gets compiled only if that page has changed. If there is a change in the included JSP file, the source JSP file will not be compiled and therefore the modification will not get reflected in the output.
  • <jsp:include page=”relativeURL” /> is the JSP include action element.The jsp:include action element is like a function call. At runtime, the included file will be ‘executed’ and the result content will be included with the soure JSP page. When the included JSP page is called, both the request and response objects are passed as parameters.If there is a need to pass additional parameters, then jsp:param element can be used. If the resource is static, its content is inserted into the calling JSP file, since there is no processing needed.

Session tracking in Servlets is done by using Interface HttpSession. It helps to identify a client throughout many page requests or visiting a website and to store details about that client.

One of the recommended approaches is HTTP session. A request is being identified by the session which is originated from similar browser during the conversation time period. Same session could be shared by all servlets. The JSESSIONID gets generated by server and is passed via cookies to the client, Built in SSL mechanism or URL rewriting (if cookies get off). For minimizing the object’s size stored in session, care shall be taken.

To obtain the session in Java servlet proceed as following:

HttpSession session = request.getSession();

  • If user already has a session  the existing session is returned.
  • If no session exists a new one is created and returned.
  • If you want to know if this is a new session:

call the Session isNew() method.

Use the following ways to pass control of a request from one servlet to another or one jsp to another.

  • First is RequestDispatcher object‘s forward method to pass the control.
  • Second is response.sendRedirect method.

When a JSP include directive is used, the included file’s code is added into the added JSP page at page translation time, this happens before the JSP page is translated into a servlet. While if any page is included using action tag, the page’s output is returned back to the added page. This happens at runtime.

System.out goes to ‘client side’ and is seen in browser, while System.err goes to ‘server side’ and is visible in error logs and/or on console.

  • The destroy() method is called only once at the end of the life cycle of a servlet.
  • This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
  • After the destroy() method is called, the servlet object is marked for garbage collection.

It can be used to “clean up” environments such as database connections.

public void destroy()

{

// Finalization code…

}

  • Servlets are implemented using java language so these have platform independent feature.
  • These are faster than CGI
  • These have declarative security management feature

It is server side component,so servlets inherit the security provided by web server

  • Cache static data using jspInit() method.
  • Release static data in jspDestroy() method.
  • To concatenate string use, StringBuffer.
  • Do not use println() method.
  • Do not use PrintWriter to send binary data. Use ServletOutputStream.
  • Always flush data in sections.
  • Use getLastModified() method to handle browser and server cache.
  • Use application server cache.
  • Use session in following order: HttpSession, Hidden fields, Cookies, URL rewriting.
  • Always remove HttpSession explicitly.
  • Disable Servlet auto reloading.

You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.

Yes, of course you can use the constructor instead of init(). 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.

  • init() is called whenever the servlet is loaded for the first time into the webserver.it performs certain one time activities which are required during the lifetime of the servlet.It may be some initialisation of variables or a database connection.
  • Destroy will be called whenever the servlet is removed from the webserver. Various resources which are held by the servlet will be released,database connections which were opened will be closed.Later the servlet is destroyed.

Typically, a default inactivity lease period for all sessions is set within your JSPengine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis.This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created.

Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.

The <jsp:forward> action enables you to forward the request to a static HTML file, a servlet, or another JSP.

<jsp:forward page=”url” />

The JSP that contains the <jsp:forward> action stops processing, clears its buffer, and forwards the request to the target resource. Note that the calling JSP should not write anything to the response prior to the <jsp:forward> action.

You can also pass additional parameters to the target resource using the <jsp:param> tag.

<jsp:forward page=”test.htm” >

<jsp:param name=”name1″ value=”value1″ />

<jsp:param name=”name2″ value=”value2″ />

</jsp:forward>

In this example, test.jsp can access the value of name1 using request.getParameter(“name1”).

To “include” another resource with a JSP, you have two options: the include directive and the include action.The include directive executes when the JSP is compiled, which parses any JSP elements in the included file for a static result that is the same for every instance of that JSP. The syntax for the include directive is

<@ include file=”some-filename” %>.

The include action, on the other hand, executes for each client request of the JSP, which means the file is not parsed but included in place. This provides the capability to dynamically change not only the content that you want to include, but also the output of that content. The syntax for the include action is <jsp:include page=”some-filename” flush=”true” />. Note that the flush attribute must always be included (in JSP 1.1) to force a flush of the buffer in the output stream.

You can also pass parameters to the included file using the same process

<jsp:forward> action:

<jsp:include page=”template.htm” flush=”true” >

<jsp:param name=”name1″ value=”value1″ />

</jsp:include>

During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.

  • Every java class will have aleast one constructor and servlets are no exception to this.
  • But while using servlets ,we never instantiate the servlet rather the container does it for us by using the newInstance() defined in the Class class;  which in turn uses the empty(Default) constructor to create a new instance of the servlet.
  • If we define parameterised constructor in the serlet ,then container will fail in instantiating the servlet.
  • The rest is left for you to decide whether a servlets need a user defined constructor or not.

To develop a web application we need to handle multiple request and give the particular page, Servlet can handle multiple requests concurrently, and can synchronize requests

The context-param element contains the declaration of a web application’s servlet context initialization parameters.

Namevalue

The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.

public void doPost (HttpServletRequest request, HttpServletResponse response)

{
try {

govi.FormBean f = new govi.FormBean();

String id = request.getParameter(“id”);

f.setName(request.getParameter(“name”));

f.setAddr(request.getParameter(“addr”));

f.setAge(request.getParameter(“age”));

//use the id to compute

//additional bean properties like info

//maybe perform a db query, etc.

// . . .

 

f.setPersonalizationInfo(info);
request.setAttribute(“fBean”,f);
getServletConfig().getServletContext()

.getRequestDispatcher(“/jsp/Bean1.jsp”).forward(request, response);

}

catch (Exception ex) {}

}

The JSP page Bean1.jsp can then process fBean, after first extracting it from the default requestscope via the useBean action.

  • <jsp:useBean id=”fBean”class=”govi.FormBean” scope=”request”/>
  • <jsp:getPropertyname=”fBean” property=”name”/>
  • <jsp:getProperty name=”fBean” property=”addr”/>
  • <jsp:getProperty name=”fBean” property=”age”/>
  • <jsp:getProperty name=”fBean” property=”personalizationInfo”/>

You can use a client-side Refresh or Server Push.

A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.

A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.

The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.

sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect also kills the session variables

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 re listed below:

  • request :It represents the request made by the client. The request implicit object is generally used to get request parameters, request attributes, header information and query string values.
  • response :The JSP implicit response object is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. It represents the response to be given to the client. The response implicit object is generally used to set the response content type, add cookie and redirect the response.
  • pageContext : This is used to access page attributes and also to access all the namespaces associated with a JSP page. The lass or the interface name of the object PageContext is jsp.pageContext. The object PageContext is written: Javax.servlet.jsp.pagecontext The PageContext object has a page scope. It is an instance of the javax.servlet.jsp.PageContext class.
  • session :The session object has a scope of an entire HttpSession. It is an instance of the javax.servlet.http.HttpSession class. It represents the session created for the requesting client, and stores objects between client’s requests. The session object views and manipulates session information, such as the session identifier, creation time, and last accessed time. It also binds objects to a session, so that the user information may persist across multiple user connections.
  • application :The application object has an application scope. It is an instance of the javax.servlet.ServletContext class. It represents the context within which the JSP is executing. It defines a set of methods that a servlet uses to communicate with its servlet container.
  • out :The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter class. It represents the output content to be sent to the client. The out implicit object is used to write the output content.
  • config :The JSP implicit config object is an instance of the java class that implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the initialization parameters available.
  • page :The Page object denotes the JSP page, used for calling any instance of a Page’s servlet. The class or the interface name of the Page object is jsp.HttpJspPage. The Page object is written: Java.lang.Object.
  • exception :The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It represents the occured exception that caused the control to pass to the JSP error page.

Servlets are not thread safe. If you want to make it Servlet as Thread safe, you can implement SingleThreadInterface.

There are two different ways of making a servlet thread safe namely

  • By implementing SingleThreadModel:
    • By implementing a SingleThreadModel it will be possible to create a Thread safe servlet.There can only be one user at a given point of time.
  • Synchornize the part of sensitive code:

We can allow a single user at a given point of time by making that part of the code which is sensitive as synchronized

ServletConfig: 

  • One ServletConfig Object is created per servlet
  • It can be used to access ServletContext
  • Parameters are configured in DD(deployment description)

ServletContext

  • One ServletContext will be created per web application.
  • Can be used to access web app parameter.
  • Can be used to get server Info.
  • Request parameters are the result of submitting an HTTP request with a query string that specifies the name/value pairs, or of submitting an HTML form that specifies the name/value pairs. The name and the values are always strings. For example, when you do a post from html, data can be automatically retrieved by using getParameter(). Parameters are Strings, and generally can be retrieved, but not set.
  • Let’s take a real example, you have one html page named htmland JSP page named Register.jsp. The RegisterForm.html contains a form with few parameters for user registration on web application and those parameters you want to store in database.

<html>

<body>

<form name=”regform” method=”post” action=”../Register.jsp”>

<table ID=”Table1″>

<tr>

<td>

First Name : <input type=”text” name=”FIRSTNAME” size=”25″ value=””>

</td>

</tr>

<tr>

<td>

<input type=”Submit” NAME=”Submit” value=”Submit” >

</td>

</tr>

</table>

</form>

</body>

</html>

When user will enter first name in the text filed and press submit button, it will callRegister.jsp page. Now you want the value entered in text field by user in jsp/servlet so there you use request.getParameter() method.

<%

String lFirstName = request.getParameter(“FIRSTNAME”);

……………….

%>

On the server side, the request.getParameter() will retrieve a value that the client has submitted in the First Name text field. Using this method you can retrive only one value. This method i.e. getParameter method is in ServletRequest interface which is part of javax.servlet package.

Request attributes (more correctly called “request-scoped variables”) are objects of any type that are explicitly placed on the request object via a call to the setAttribute() method. They are retrieved in Java code via the getAttribute() method and in JSP pages with Expression Language references. Always use request.getAttribute() to get an object added to the request scope on the serverside i.e. using request.setAttribute().

Attributes are objects, and can be placed in the request, session, or context objects. Because they can be any object, not just a String, they are much more flexible. You can also set attributes programaticly and retrieve them later. This is very useful in the MVC pattern. For example, you want to take values from database in one jsp/servlet and display them in another jsp. Now you have resultset filled with data ready in servlet then you use setAttributemethod and send this resultset to another jsp where it can be extracted by using getAttributemethod.

Once a servlet gets a request, it can add additional attributes, then forward the request off to another servlet for processing. Attributes allow servlets to communicate with one another.

Life-cycle methods of the JSP are:

  • jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
  • _jspService():The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann’t be overridden.

The container calls this when its instance is about to destroyed.The jspInit() and jspDestroy() methods can be overridden within a JSP page.

ServletContext: Gives the information about the container

PageContext: Gives the information about the Request

No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients.

A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not.

Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

  • Declaring variables in JSP pages are not thread-safe. The declared variables in JSP pages end-up as instance variables in the converted Servlets. <%! Calendar c = Calendar.getInstance(); %>
  • Decalring instance variables in Servlets is not thread safe, as Servlets are inherently multi-threaded and gets accessed by multiple-threads. Same is true for the Actionclasses in the struts framework.
  • Some of the Java standard library classes likeSimpleDateFormat is not thread-safe. Always check the API to see if a particular class is thread-safe. If a particular class or library is not therad-safe, you could do one of three things.

Provide your own wrapper class that decorates the third-party library with proper synchronization.

This is a typical use of the decorator design pattern.

Use an alternative library, which is thread-safe if available.

For example, Joda Time Library.

Use it in a thread-safe manner.

For example, you could use the SimpleDateFormat class as shown below within a ThreadLocal class.

Each thread will have its own instance of the SimpleDateFormat object.

 

public class DateFormatTest

{

//          anonymous inner class. Each thread will have its own copy

 

private final static ThreadLocal<SimpleDateFormat> shortDateFormat

=  new ThreadLocal<SimpleDateFormat>()

{

protected SimpleDateFormat initialValue()

{

return new SimpleDateFormat(“dd/MM/yyyy”);

}

};

 

public Date convert(String strDate)throws ParseException

{

//          get the SimpleDateFormat instance for this thread and parse the date string

 

Date d = shortDateFormat.get().parse(strDate);

return d;

}

}

  • The one that is very popular with the interviewers is writing the singleton classes that are not thread-safe.