java

37
TALENTSPRINT | © Copyright 2015 Java Course: Developing Presentation Tier of an Enterprise Application using JSP Session: ServletConfig, ServletContext, HTTPSession

Transcript of java

TALENTSPRINT | © Copyright 2015

Java

Course: Developing Presentation Tier of an Enterprise Application

using JSP

Session: ServletConfig, ServletContext, HTTPSession

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

By the end of this session, you will be able to understand:

• ServletContext Interface

• Advantage of ServletContext

• Example of ServletContext

• ServletConfig Interface

• Advantage of ServletConfig

• Example of ServletConfig

• HTTP and Session Management

• Web Container Session

• Obtaining Session object

• Setting Information to the Session

• Getting information from Session

• Deleting Session from Session

• Invalidating Session

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Consider a situation when database connection coding has to be modified in several servlets

Oh! So much time is getting wasted in

changing all these servlet code

ServletContext and ServletConfig

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Servlet API should provide something to avoid duplicate coding.

Then how to simplify this??

ServletContext and ServletConfig

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

WEB-INF

classes

lib

Solution is to use

ServletContext and ServletConfig

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

ServletContext

MyWebSite

WEB-INF

classes

lib

Main Path or Root Path is “MyWebSite”.

“MyWebSite” could be accessed by ServletContext interface object.

ServletContext object is global to the web application.

ServletContext is created at the time of web application is deployed by the Container.

As long as web application is executing scope of ServletContext object will be available.

Only one object per web application will be created.

ServletContext and ServletConfig

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

ServletContext Advantages

MyWebSite

WEB-INF

classes

lib

We can pass same information to all servlets.

For example Database connection.

Global parameters are passed through web.xml.

<context-param> tag under <web-app> will provide global parameters.

Change in <context-param> will effect to the web application.

We can write many <context-param> tag to provide multiple global parameters.

ServletContext and ServletConfig

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

The ServletContext API

ServletContext and ServletConfig

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

• ServletContext is a interface which helps us to communicate with the servlet container

• There is only one Servlet Context for the entire web application and the components of the web application can share it.

Getting Context Parameter Names

ServletContext and ServletConfig

• First of all the web container reads the deployment descriptor file and then creates a name/value pair for each <context-param> tag.

• After creating the name/value pair it creates a new instance of ServletContext.

• Its the responsibility of the Container to give the reference of the ServletContext to the context init parameters.

• The servlet and jsp which are part of the same web application can have the access of the ServletContext.

Web application initialization:

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

<web-app>

.........

.........

<context-param>

<param-name>Company</param-name>

<param-value>TalentSprint</param-value>

</context-param>

<context-param>

<param-name>Address</param-name>

<param-value>IIIT Campus</param-value>

</context-param>

.........

.........

</web-app>

ServletContext and ServletConfig

Context Parameter Names in web.xml

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

public class GettingContextParameterNames extends HttpServlet {

private String cnm = "";

private String address = "";

public void init(ServletConfig config) throws ServletException {

super.init(config);

ServletContext context = getServletContext();

cnm = context.getInitParameter("company");

address = context.getInitParameter("address");

}

public void doGet(HttpServletRequest req, HttpServletResponse

res)

throws IOException {

ServletOutputStream out = res.getOutputStream();

res.setContentType("text/html");

out.println("Company Name: " + cnm);

out.println("Address: " + address);

}

}

ServletContext and ServletConfig

Read Context Parameter Names in Servlet

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Perfect, But if I want to do with single servlet or some servlets?

Umm! Let me check again Servlet API, there should be

some interface or class

ServletContext and ServletConfig

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

MyWebSite

WEB-INF

classes

lib

It is initialized by the Container

It is used to initialize a single servlet using init() method.

We can pass initialization parameters to a servlet using web.xml file.

Only one ServletConfig object per servlet will be created.

public void

init(ServletConfig sc)

throws ServletException{

super.init(sc);

}

Solution is to use

<param-name> and <param-value> tags under servlet will provide servlet wide parameters.

ServletContext and ServletConfig

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

<web-app>

.........

.........

<servlet>

<init-param>

<param-name>Admin</param-name>

<param-value>TalentSprint</param-value>

</init-param>

</servlet>

.........

.........

</web-app>

ServletContext and ServletConfig

Init Parameter Names in web.xml

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

public class GettingInitParameterNames extends HttpServlet {

private String admin = "";

public void init(ServletConfig config) throws

ServletException {

super.init(config);

admin = config.getInitParameter("Admin");

}

public void doGet(HttpServletRequest req, HttpServletResponse

res)

throws IOException {

ServletOutputStream out = res.getOutputStream();

res.setContentType("text/html");

out.println("Admin Name: " + admin);

}

}

ServletContext and ServletConfig

Read Init Parameter Names in Servlet

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

• A ServletContext object is the runtime representation of the web application

• It is a window for a servlet to view it's environment

• A servlet can use this interface to get information such as initialization parameters for the web application or servlet container's version

• Every web application has one and only one ServletContextand is accessible to all active resource of that application.

• ServletConfig is related a specific Servlet

• ServletConfig consists all init parameters from web.xml file related to that servlet

ServletContext and ServletConfig

ServletContext and ServleConfig Interfaces

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

ServletContext and ServletConfig

ServletContext and ServleConfig Interfaces

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

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

• ServletConfig is a servlet configuration object used by a servlet container used to pass information to a servlet during initialization. All of its initialization parameters can ONLY be set in deployment descriptor

• The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.

• The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application.

• ServletContext has a APPLICATION SCOPE .. [GLOBALLY ACCESSIBLE ACROSS THE PAGES] where as ServletConfig has a SESSION SCOPE.. [LOCAL SCOPE......which is mostly used for intialising purpose].

Difference Between ServletContext and ServletConfig

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Internet

Let us understand how HTTP(Hyper Text Transfer Protocol) works

Request Response

For every new request made by the client, server generates a new response

Session Management

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

So what is the problem if HTTP generates a new response always ?

It immediately forgets about previous page contents

So What ?

Session Management

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Alone HTTP will not be able to maintain shopping cart like this

Because HTTP is a stateless protocol

Session Management

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Ok I amtaking your order

Using Session

Client can talk with the server

This is known as Conversational state with the server

Take this ID(123) to place orders

Server remember whatever client says

Session Management

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

HTTP and Session Management

• HTTP is a stateless protocol.

• Each request and response message connection is independent of all others.

• Therefore, the web container must create a mechanism to store session information for a particular user.

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Web Container Sessions

The web container can keep a session object for each user:

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Using Session Management in a Web Application

• Each activity-specific action must store attributes (name/object pairs) that are used by other requests within the session.

• Any action can access an attribute that has already been set by processing a previous request.

• At the end of the session, the action might destroy the session object.

Using session management

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Session API

• Your action controller accesses the session object through the request object.

• You can store and access any number of objects in the session object.

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Storing Session Attributes

• Get session object using getSession() method of HttpServletRequest interface

• HttpSession session = request.getSesison();

• Add attribute in session:

Session.setAttribute(“suser”, user);

− suser: session attribute name

− user: variable which you want to store as session

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

• Get session object using getSession() method of HttpServletRequest interface

• HttpSession session = request.getSesison();

• Get attribute from session:

Session.getAttribute(“suser”);

− suser: session attribute name

Storing Session Attributes

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Destroying the Session

• You can control the lifespan of all sessions using the deployment descriptor:

</web-app>

• You can control the lifespan of a specific session object using the following APIs:

«interface»HttpSession

invalidate()getCreationTime() :longgetLastAccessedTime() :longgetMaxInactiveInterval() :intsetMaxInactiveInterval(int)

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

• Session objects can be shared across multiple actions (for different use cases) within the same web application.

• Session objects are not shared across multiple web applications within the same web container.

• Destroying a session using the invalidate method might cause disruption to other servlets (or use cases).

Destroying the Session

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Using Cookies for Session Management

• Cookies are sent in a response from the web server.

• Cookies are stored on the client’s computer.

• Cookies are stored in a partition assigned to the web server’s domain name. Cookies can be further partitioned by a path within the domain.

• All cookies for that domain (and path) are sent in every request to that web server.

• Cookies have a lifespan and are flushed by the client browser at the end of that lifespan.

IETF RFC 2109 creates an extension to HTTP to allow a web server to store information on the client machine:

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Cookie API

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Using Cookies Example

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

Cookie c = new Cookie("yourname", name);

response.addCookie(c);

The code to store a cookie in the response:

Cookie[] allCookies = request.getCookies();

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

if ( allCookies[i].getName().equals(“yourname”) ) {

name = allCookies[i].getValue();

}

}

The code to retrieve a cookie from the request:

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Performing Session Management Using Cookies

• The cookie mechanism is the default session management strategy.

• There is nothing special that you code in your servlets to use this session strategy.

• Unfortunately, some users turn off cookies on their browsers.

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Using URL-Rewriting for Session Management

• URL-rewriting is used when cookies cannot be used.

• The server appends extra data on the end of each URL.

• The server associates that identifier with data it has stored about that session.

• With this URL:

http://host/path/file;jsessionid=123 session information is jsessionid=123.

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

Using URL-Rewriting for Session Management

TALENTSPRINT | © Copyright 2015

ServletConfig, ServletContext, HTTPSession

URL-Rewriting Implications

• Every HTML page that participates in a session (using URL-rewriting) must include the session ID in all URLs in those pages. This requires dynamic generation.

• Use the encodeURL method on the response object to guarantee that the RLs include the session ID information.

• For example, in the EnterPlayerForm view the action attribute on the form tag must be encoded:

86.// Present the form

87.out.println(“<form action=’”

88. + response.encodeURL(“enter_player.do”)

89. + “‘ method=’POST’>”);