IAT-2 Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Explain the lifecycle of a servlet.

 Java Servlets are programs that run on a Web or Application server


 Act as a middle layer between a request coming from a Web browser or other HTTP client and
databases or applications on the HTTP server.
 Using Servlets, you can collect input from users through web page forms, present records from
a database or another source, and create web pages dynamically.
 Servlets are server side components that provide a powerful mechanism for developing web
application

Servlet Life Cycle

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 () method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in details.

The init() method :


 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.
 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...
}
The service() method :

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

Signature of service method:


public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
}

 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 is
the signature of these two methods.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has no METHOD
specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and it should be
handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}

The destroy() method :


 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. The
destroy method definition looks like this:

public void destroy() {


// Finalization code

2. How do you use Tomcat for Servlet development?


Steps to Create Servlet Application using tomcat server
To create a Servlet application you need to follow the below mentioned steps. These steps are common for
all the Web server. In our example we are using Apache Tomcat server. Apache Tomcat is an open source
web server for testing servlets and JSP technology. Create directory structure for your application.
1. Create directory structure for your application.
2. Create a Servlet
3. Compile the Servlet
4. Create Deployement Descriptor for your application
5. Start the server and deploy the application
1. Creating the Directory Structure
Sun Microsystem defines a unique directory structure that must be followed to create a servlet application.

Create the above directory structure inside Apache-Tomcat\webapps directory.


All HTML, static files(images, css etc) are kept directly under Web application folder.

While all the Servlet classes are kept inside classes folder.

The web.xml (deployement descriptor) file is kept under WEB-INF folder.


2. Creating a Servlet

There are three different ways to create a servlet.


• By extending HttpServlet class
• By extending GenericServlet class
• By implementing Servlet interface

import javax.servlet.*;
import
javax.servlet.http.*;
import java.io.*;

// extending HttpServlet class

public MyServlet extends HttpServlet


{ public void doGet(HttpServletRequest request,HttpServletResposne response)
throws ServletException

{ response.setContentType("text/html"); // set content


type

//get the stream to write the data


PrintWriter out = response.getWriter(); // create printwriter object out.println("<h1>Hello
Readers</h1>"); // print ur content on client web browser

}
}
Write above code and save it as MyServlet.java anywhere on your PC. Compile it from there and
paste the class file into WEB-INF/classes/ directory that you have to create inside

Tomcat/webapps directory.

import javax.servlet.*;
import java.io.*;
// extending GenericServlet class

public MyServlet extends GenericServlet


{ public void service(ServletRequest request,ServletResponse
response)

throws IOException,ServletException{
{ response.setContentType("text/html"); // set content
type

//get the stream to write the data


PrintWriter out = response.getWriter(); // create printwriter object out.println("<h1>Hello
Readers</h1>"); // print ur content on client web browser

}
}

3. Compiling a Servlet
To compile a Servlet a JAR file is required. Different servers require different JAR files. In Apache Tomcat
server servlet-api.jar file is required to compile a servlet class.

□ Download servlet-api.jar file.


□ Paste the servlet-api.jar file inside Java\jdk\jre\lib\ext directory.

NOTE: After compiling your Servlet class you will have to paste the class file into WEB-INF/classes/ directory.

4. Create Deployment Descriptor


Deployment Descriptor(DD) is an XML document that is used by Web Container to run Servlets and JSP
pages. web.xml file

<web-app>
<servlet>
<servlet-name> MyServlet </servlet-name>
<servlet-class> MyServlet </servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> MyServlet </servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

5. Starting Tomcat Server for the first time set JAVA_HOME or JRE_HOME in environment
variable (It is required to start server).

Go to My Computer properties -> Click on advanced tab then environment variables -> Click on the
new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable
value -> ok

Run Servlet Application


Open Browser and type http:localhost:8080/First/hello
1. What is Cookie? Explain creation of Cookie and retrieving information
from cookie using code snippets?
Cookies
 A cookie is a small piece of information that is persisted between the multiple client
requests.
 A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
• Typical Uses of Cookies
– Identifying a user during an e-commerce session
 Servlets have a higher-level API for this task.
– Avoiding username and password
– Customizing a site
– Focusing advertising
Create a Cookie object.
– Call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie c = new Cookie("userID", "a1234");
• Set the maximum age.
– To tell browser to store cookie on disk instead of just In memory, use setMaxAge (argument is in
seconds)
c.setMaxAge(60*60*24*7); // One week
• Place the Cookie into the HTTP response
– Use response.addCookie.
– If you forget this step, no cookie is sent to the browser!
response.addCookie(c);

Call request.getCookies
– This yields an array of Cookie objects.
• Loop down the array, calling getName on each entry until you find the cookie of interest
– Use the value (getValue) in application-specific way.
Constructor of Cookie class
Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String constructs a cookie with a specified name and value.
value)

Useful Methods of Cookie class


There are given some commonly used methods of the Cookie class.

Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)

public String getName() Returns the name of the cookie. The name cannot be changed
after creation.

public String getValue() Returns the value of the cookie.

public void setName(String changes the name of the cookie.


name)

public void setValue(String changes the value of the cookie.


value)

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add


cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.

Program
index.html
<form method="post" action=" MyServlet ">
Name:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>

MyServlet.java public class MyServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) {


// . . . . .

String name = request.getParameter("user");


String pass = request.getParameter("pass");

if(pass.equals("1234"))
{
Cookie ck = new Cookie("username",name);
response.addCookie(ck);

//response.sendRedirect("First");//call ur servlet

//creating submit button


out.print("<form action= First >");

out.print("<input type='submit' value='go'>");

out.print("</form>);
}

}
}

First.java public class First extends


HttpServlet { protected void
doGet(HttpServletRequest request,
HttpServletResponse response) { // .
..

Cookie[] cks = request.getCookies();


out.println("Welcome "+cks[0].getValue()); }
}
Describe the classes and interfaces of javax.servlet package.
Servlet API consists of two important packages that encapsulates all the important
classes and interface,namely :
1. javax.servlet.*;

INTERFACES CLASSES
Servlet- ServletInputStream
ServletContext -ServletOutputStream
ServletConfig -ServletException
ServletRequest- UnavailableException
ServletResponse- GenericServlet

Interface Summary

Servlet Defines methods that all servlets must implement.

ServletRequest -Defines an object to provide client request information to a servlet.

ServletResponse- Defines an object to assist a servlet in sending a response to the client.

ServletConfig

A servlet configuration object used by a servlet container to pass information to a

servlet during initialization.

ServletContext Defines a set of methods that a servlet uses to communicate with its servlet

container, for example, to get the MIME type of a file, dispatch requests, or write

to a log file.
Interface Servlet

Interface
ServletRequest

Interface ServletResponse
Interface ServletConfig

Interface ServletContext

Class Summary

GenericServlet Defines a generic, protocol-independent servlet.

ServletInputStream Provides an input stream for reading binary data from a client request,
including an efficient readLine method for reading data one line at a time.
ServletOutputStream Provides an output stream for sending binary data to the client.

ServletException Defines a general exception a servlet can throw when it encounters


difficulty.
UnavailableException Defines an exception that a servlet or filter throws to indicate that it is
permanently or temporarily unavailable.

Class GenericServlet
java.lang.Object
javax.servlet.GenericServlet
All Implemented Interfaces: Servlet, ServletConfig

Class ServletInputStream
java.lang.Object
java.io.InputStream

javax.servlet.ServletInputStream
Method Summary

int readLine(byte[] b, int off, int len)


Reads the input stream, one line at a time.

Class ServletOutputStream
Method Summary

void println()

void print(java.lang.String s)
Writes a String to the client, without a carriage return-line feed (CRLF) character at the
end.
void println()
Writes a carriage return-line feed (CRLF) to the client.

void println(java.lang.String s)
Writes a String to the client, followed by a carriage return-line feed (CRLF).

Describe the classes and interfaces of javax.servlet.http package.

CLASSES
INTERFACES

Cookie HttpServletRequest

HttpServlet HttpServletResponse

HttpSessionBindingEvent HttpSession

Interface Summary

HttpServletRequest Extends the ServletRequest interface to provide request information for


HTTP servlets.

HttpServletResponse Extends the ServletResponse interface to provide HTTP-specific


functionality in sending a response.

HttpSession Provides a way to identify a user across more than one page request or
visit to a Web site and to store information about that user.

Interface HttpServletResponse
HttpServletRequest

Interface HttpServletRequest :
interface HttpSession
Class Summary

Cookie Creates a cookie, a small amount of information sent by a servlet to a Web


browser, saved by the browser, and later sent back to the server.

HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet


suitable for a Web site.

Events of this type are either sent to an object that implements


HttpSessionBindingListener when it is bound or unbound from a session,
or to a HttpSessionAttributeListener that has been configured in the
HttpSessionBindingEvent
deployment descriptor when any attribute is bound, unbound or replaced
in a session.

HttpSessionEvent This is the class representing event notifications for changes to sessions
within a web application

Class Cookie
class HttpServlet:
Class HttpSessionBindingEvent

Method Summary

java.lang.String getName()
Returns the name with which the attribute is bound to or unbound from the
session.

HttpSession getSession()
Return the session that changed.

java.lang.Object getValue()
Returns the value of the attribute that has been added, removed or replaced.

Class HttpSessionEvent
Method Summary

HttpSession getSession()
Return the session that changed.
With an example program Explain the mechanism of SessionTracking
in Servlets?
HttpSession object is used to store entire session with a specific client. We can store, retrieve
and remove attribute from HttpSession object. Any servlet can have access to HttpSession
object throughout the getSession() method.

Some Important Methods of HttpSession

Methods Description
returns the time when the session was created, measured in
long getCreationTime()
milliseconds since midnight January 1, 1970 GMT.

returnsa string containing the unique identifier assigned to the


String getId()
session.
int getMaxInactiveInterval() returns the maximum time interval, in seconds.
void invalidate() destroythe session
booleanisNew() returnstrueif the session is new else false

Example

index.html
<form method="post" action="Validate">
User: <input type="text" name="uname "
/><br/>
<input type="submit" value="submit">
</form>

Validate.java public class Validate extends HttpServlet {

protected void doPost(request, response)


{
// . . . .
String name = request.getParameter("user");
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", uname);
response.sendRedirect("Welcome");

}
}

Welcome.java
public class Welcome extends HttpServlet {

protected void doGet(request, response){


// . . . .
HttpSession session =
request.getSession(); String user =
(String)session.getAttribute("user");
out.println("Hello "+user);
}
}
What is JSP? What are different JSP tags demonstrate with an
example.
JSP

• Java Server Page technology is used to create dynamic web applications.


• JSP pages are easier to maintain then a Servlet.
• JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while
JSP  adds Java code inside HTML using JSP tags.
• Everything a Servlet can do, a JSP page can also do it.
• JSP enables us to write HTML pages containing tags, inside which we can include
powerful Java programs .

There are five different types of scripting elements

1. JSP scriptlet tag A scriptlet tag is used to execute java source code in
JSP. <% java source code %>

In this example, we are displaying a welcome message.

<html>

<body>

<% out.print("welcome to jsp"); %>

</body>

</html>

2. JSP Declaration Tag


The JSP declaration tag is used to declare variables, objects and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.

So it doesn't get memory at each request.

<%! field or method declaration %>

3. JSP Expression Tag


Expression Tag is used to print out java language expression that is put between the tags. An
expression tag can hold any java language expression that can be used as an argument to the
out.print() method. Syntax of Expression Tag

<%= JavaExpression %>

<%= (2*5) %> //note no ; at end of statement.


4. JSP directives
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.

Syntax <%@ directive attribute="value"


%> There are three types of directives:
A. import directive
B. include directive C. taglib directive
a. import
The import attribute is used to import class,interface or all the members of a package.It is
similar to import keyword in java class or interface.
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>

b. Include Directive
The include directive tells the Web Container to copy everything in the included file and paste it
into current JSP file. The include directive is used to include the contents of any resource it may
be jsp file, html file or text file. Syntax of include directive is:

<%@ include file="filename.jsp" %>

c. JSP Taglib directive


The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags
and a tag library is a set of user-defined tags that implement custom behavior. The taglib
directive declares that your JSP page uses a set of custom tags, identifies the location of the
library, and provides means for identifying the custom tags in your JSP page.

syntax <%@ taglib uri = "uri" prefix = "prefixOfTag" >


For example, suppose the custlib tag library contains a tag called hello. If you wanted to use the
hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be used in your JSP
file as follows

<%@ taglib uri = "http://www.example.com/custlib" prefix = "mytag" %>

<html>

<mytag:hello/>
<
/
bod
y>
</h
tml
>

5. JSP Comments
JSP comment marks text or statements that the JSP container should
ignore. syntax of the JSP comments <%- - This is JSP comment - -%>

index.html
<form action="welcome.jsp">

<input type="text" name="uname">

<input type="submit" value="go"><br/> </form> welcome.jsp

<%

String name=request.getParameter("uname");
out.print("welcome "+name);

%>

</html>

welcome.jsp

<html>
<body> <%
String name=request.getParameter("uname");
out.print("Welcome "+name); session.setAttribute("user",name);

<a href="second.jsp">second jsp page</a>

%>
</body>

What is String? Explain all String Constructors available with code


snippets.
Differentiate between Get and Post methods.
GET Request POST Request

Data is sent in header to the server Data is sent in the request body

Get request can send only limited amount of data Large amount of data can be sent.

Get request is not secured because data is exposed Post request is secured because data is not
exposed in URL in URL.

Differentiate between JSP and Servlets.

You might also like