Working with Servlets

30
Slide 1 of 30 © People Strategists www.peoplestrategists.com Working with Servlets

Transcript of Working with Servlets

Page 1: Working with Servlets

Slide 1 of 30© People Strategists www.peoplestrategists.com

Working with Servlets

Page 2: Working with Servlets

Slide 2 of 30© People Strategists www.peoplestrategists.com

Objectives

In this session, you will learn to:

Explore the ServletConfig interface

Explore the ServletContext interface

Implement ServletContext Inerface

Introduce session tracking

Implement session tracking

Page 3: Working with Servlets

Slide 3 of 30© People Strategists www.peoplestrategists.com

The ServletConfig interface:

Is implemented by a Web container during the initialization of a

servlet to pass the configuration information to a servlet.

Is passed to the init()method of the servlet during initialization.

Can be used to pass initialization parameters to the servlets.

The initialization parameters are passed as name-value pairs.

For example, the connection URL can be passed as an initialization parameter of the servlet.

Exploring the ServletConfig Interface

Page 4: Working with Servlets

Slide 4 of 30© People Strategists www.peoplestrategists.com

The following table describes the various methods defined in the ServletConfig interface:

Exploring the ServletConfig Interface (Contd.)

Method Description

String getInitParameter(String

param)It returns a String object containing the value of the initialization parameters.

Enumeration<String>

getInitParameterNames()It returns the names of all the initialization parameters as an enumeration of Stringobjects.

ServletContext getServletContext() It returns the ServletContext object for the servlet in which the caller is executing.

String getServletName() It returns a String object containing the name of the servlet instance.

Page 5: Working with Servlets

Slide 5 of 30© People Strategists www.peoplestrategists.com

The ServletContext provides the environmental information to the servlets in which they are running.

Each Web application consists of only one ServletContextobject.

A ServletContext object is also known as a Web context.

The Web container creates an object of ServletContext at time of deploying the project.

Following figure shows the creation of ServletContext object.

Exploring the ServletContext Interface

ServletContext Object Creation

Page 6: Working with Servlets

Slide 6 of 30© People Strategists www.peoplestrategists.com

The following table describes the various methods defined in the ServletContext interface:

Exploring the ServletContext Interface (Contd.)

Method Description

public void setAttribute(String,

Object)Binds the object with a name and stores the name/value pair as an attribute of the ServletContext object. If an attribute already exists, this method replaces the existing attribute.

public Object getAttribute(String

attrname)Returns the object stored in the ServletContext object with the name passed as a parameter.

public Enumeration

getAttributeNames()

Returns an enumeration of the Stringobject that contains names of all the context attributes.

public String

getInitParameter(String pname)Returns the value of the initialization parameter with the name passed as a parameter.

public Enumeration

getInitParameterNames()Returns an enumeration of String object that contains names of all the initialization parameters.

Page 7: Working with Servlets

Slide 7 of 30© People Strategists www.peoplestrategists.com

Usage of the ServletContext interface:

The ServletContext object provides an interface between the

container and servlet.

It can be used to get configuration information from the web.xml

file.

It can be used to set, get or remove attribute from the web.xml file.

It can be used to provide inter-application communication.

You can access ServletContext object using the getServletContext method of:

The ServletConfig interface,

The GenericServlet class

The HttpServletRequest interface

Exploring the ServletContext Interface (Contd.)

Page 8: Working with Servlets

Slide 8 of 30© People Strategists www.peoplestrategists.com

Accessing ServletContext object using the getServletContext method of the ServletConfig interface:

You can use the following code snippet to get the ServletContext

object:

In the preceding code snippet,

The getServletConfig method returns the object of

ServletConfig.

Thereafter, the conf object calls getServletContext that returns the

ServletContext object.

Implementing the ServletContext Interface

ServletConfig conf = getServletConfig();

ServletContext context = conf.getServletContext();

Page 9: Working with Servlets

Slide 9 of 30© People Strategists www.peoplestrategists.com

Consider a scenario where you need to develop a Web application that stores the email and name of user in web.xml file. In addition, you need to access those parameters using ServletContext and display them, as shown in the following figure.

Activity: Implementing the ServletContext Interface

The Expected Output

Page 10: Working with Servlets

Slide 10 of 30© People Strategists www.peoplestrategists.com

Accessing ServletContext object using the getServletContext method of the GenericServlet class:

In general, every servlet class extends HttpServlet, which is a sub

class of GenericServlet.

Use the following code snippet to access the ServletContext

object:

In the preceding code snippet, the getServletContext method

returns the ServletContext object.

Implementing the ServletContext Interface (Contd.)

ServletContext context = getServletContext();

Page 11: Working with Servlets

Slide 11 of 30© People Strategists www.peoplestrategists.com

Consider a scenario where you need to develop a Web application that fulfills the following requirements:

It should provide a user interface to accept the credentials, as shown

in the following figure.

It should validate the entered details with value stored in the

web.xml file.

Activity: Implementing ServletContext Using GenericServlet

The Expected Output

Page 12: Working with Servlets

Slide 12 of 30© People Strategists www.peoplestrategists.com

It should display welcome message if the credentials are correct, as

shown in the following figure.

Activity: Implementing ServletContext Using GenericServlet (Contd.)

The Expected Output

Page 13: Working with Servlets

Slide 13 of 30© People Strategists www.peoplestrategists.com

Accessing ServletContext object using the getServletContext method of the HttpRequestServletinterface:

You can use the following code snippet to access the

ServletContext object:

In the preceding code snippet, the req object calls the

getServletContext method that returns the ServletContext

object.

Implementing the ServletContext Interface (Contd.)

public void doGet/doPost(HttpServletRequest req,

HttpServletResponse res)

{

ServletContext ctx = req.getServletContext();

}

Page 14: Working with Servlets

Slide 14 of 30© People Strategists www.peoplestrategists.com

Consider a scenario where you need to develop a Web application that fulfills the following requirements:

It should provide a user interface to accept the customer details, as

shown in the following figure:

It should store the entered details to access database.

It should display a message “Details are saved.”

Activity: Implementing ServletContext Using HttpServletRequest

The Expected Output

Page 15: Working with Servlets

Slide 15 of 30© People Strategists www.peoplestrategists.com

Session tracking is the process of maintaining information, or state, about Web site visitors as they move from page to page.

The connection from a browser to a Web server occurs over the stateless Hypertext Transfer Protocol (HTTP).

Therefore, the Web developer has to explicitly write code to implement session tracking.

The mechanism to implement session tracking are:

HttpSession

Cookie

URL Rewriting

Introducing Session Tracking

Page 16: Working with Servlets

Slide 16 of 30© People Strategists www.peoplestrategists.com

HttpSession:

It is an interface that provides methods to handle session tracking.

A session object is created on the application server, usually in a Java servlet or a Java Server Page.

The object gets stored on the application server and a unique identifier called a session ID is assigned to it.

The object and session ID are handled by a session manager on the application server.

Each session ID assigned by the application server has zero or more key/value pairs tied to it.

The values are objects that you place in the session.

Implementing Session Tracking

Page 17: Working with Servlets

Slide 17 of 30© People Strategists www.peoplestrategists.com

The following table describes the various methods defined in the HttpSession interface:

Implementing Session Tracking (Contd.)

Method Description

public void setAttribute(String

name, Object value)Binds the object with a name and stores the name/value pair as an attribute of the HttpSession object. If an attribute already exists, this method replaces the existing attribute.

public Object getAttribute(String

name)Retrieves the String object specified in the parameter, from the session object. If no object is found for the specified attribute, the getAttribute()method returns null.

public Enumeration

getAttributeNames()Returns an Enumeration object that contains the name of all the objects that are bound as attributes to the session object.

public void

removeAttribute(String name)Removes the object bound with the specified name from this session.

public void invalidate() Invalidates this session and unbinds any objects bound to it.

public Boolean isNew() Returns a Boolean with a value of true if the client does not yet know about the session or if the client chooses not to join the session

Page 18: Working with Servlets

Slide 18 of 30© People Strategists www.peoplestrategists.com

To use HttpSession object, you need to:

Create and retrieve session object using the getSession method of HttpServletRequest.

Following code snippet shows an example:

The getSession method is passed a boolean value.

The false value indicates that you want to retrieve an existing session object.

The true value lets the session manager know that a session object needs to be created if one does not already exist.

Implementing Session Tracking (Contd.)

HttpSession session = request.getSession(true);

Page 19: Working with Servlets

Slide 19 of 30© People Strategists www.peoplestrategists.com

An object of HttpSession can find out that the session is new or can remove one.

Following code snippet shows an example:

In the above code snippet, the existing session object gets removed and a new session object is created.

Implementing Session Tracking (Contd.)

HttpSession session = request.getSession (true);

if (session.isNew() == false) {

session.invalidate();

session = request.getSession(true);

}

Page 20: Working with Servlets

Slide 20 of 30© People Strategists www.peoplestrategists.com

You need to develop a Web application that allows users to buy products online. The application should be based on the following guidelines:

It should provide a login page, as sown in the following figure.

Activity: Implementing Session Tracking Using HttpSession

The Expected Output

Page 21: Working with Servlets

Slide 21 of 30© People Strategists www.peoplestrategists.com

It should display a Web page to select brands of shirts, as sown in the following figure.

Activity: Implementing Session Tracking Using HttpSession (Contd.)

The Expected Output

Page 22: Working with Servlets

Slide 22 of 30© People Strategists www.peoplestrategists.com

It should display the bill based on the selection, as shown in the

following figure.

Activity: Implementing Session Tracking Using HttpSession (Contd.)

The Expected Output

Page 23: Working with Servlets

Slide 23 of 30© People Strategists www.peoplestrategists.com

Cookie:

Is information that is stored as a name/value pair.

Is transmitted from the server to the browser.

Is a common way of session tracking.

Cookies can be used to tie specific visitors to information about them on the server.

The Java servlet specification provides a simple cookie API that allows you to write and retrieve cookies.

Following code snippet creates a Cookie object:

The Cookie object is valid for one hour.

The response object adds the cookie for later use.

Implementing Session Tracking (Contd.)

Cookie user = new Cookie("user","Jennifer");

user.setMaxAge(3600);

response.addCookie(user);

Page 24: Working with Servlets

Slide 24 of 30© People Strategists www.peoplestrategists.com

Following code snippet retrieves the Cookie object:

The getCookies method retrieves the stored cookies.

The getName method returns the cookie name.

The getValue method returns the value stored in cookie.

Implementing Session Tracking (Contd.)

String user = "";

Cookie[] cookies = request.getCookies();

if (cookies != null) {

for (int i = 0; i < cookies.length; i++) {

if (cookies[i].getName().equals("user"))

user =cookies[i].getValue();

}

}

Page 25: Working with Servlets

Slide 25 of 30© People Strategists www.peoplestrategists.com

You need to develop a Web application that accepts the name of a user and writes it to cookie. For this, you need to create a user interface, as shown in the following figure.

Activity: Implementing Session Tracking Using Cookie

The Expected Output

Page 26: Working with Servlets

Slide 26 of 30© People Strategists www.peoplestrategists.com

In addition, you need to read the cookie value and display it, as shown in the following figure.

Activity: Implementing Session Tracking Using Cookie (Contd.)

The Expected Output

Page 27: Working with Servlets

Slide 27 of 30© People Strategists www.peoplestrategists.com

URL Rewriting:

is the lowest common denominator of session tracking.

Can be used for session tracking if client does not support cookies.

Involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session.

In URL rewriting, users append a token or identifier to the URL of the next Servlet or the next resource.

Implementing Session Tracking (Contd.)

Page 28: Working with Servlets

Slide 28 of 30© People Strategists www.peoplestrategists.com

The HttpServletResponse interface provides following two methods for URL Rewriting:

encodeURL(String):

Encodes the specified URL by including the session ID in it.

Returns the URL unchanged if encoding is not needed.

URLencodeRedirectURL(String):

Encodes the specified URL for use in the sendRedirect method.

Returns the URL unchanged if encoding is not needed.

All URLs sent to the HttpServletResponse.sendRedirectmethod should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

Implementing Session Tracking (Contd.)

Page 29: Working with Servlets

Slide 29 of 30© People Strategists www.peoplestrategists.com

Summary

In this session, you learned that:

ServletConfig is implemented by a Web container during the initialization of a servlet to pass the configuration information to a servlet.

ServletContext provides the environmental information to the servlets in which they are running.

Usage of the ServletContext interface are:

It can be used to get configuration information from the web.xml file.

It can be used to set, get or remove attribute from the web.xml file.

It can be used to provide inter-application communication.

Session tracking is the process of maintaining information, or state, about Web site visitors as they move from page to page.

The mechanism to implement session tracking are:

HttpSession

Cookie

URL Rewriting

Page 30: Working with Servlets

Slide 30 of 30© People Strategists www.peoplestrategists.com

Summary (Contd.)

HttpSession is an interface that provides methods to handle session tracking.

Cookie is information that is stored as a name/value pair and is transmitted from the server to the browser.

It Is a common way of session tracking.

URL Rewriting can be used for session tracking if client does not support cookies.

It Involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session.