Unit 2
Unit 2
element, then
define a mapping from a URL path to a servlet declaration with the
"; }
@0verride
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException {
response. setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print1n(msg);
pw.printIn("This is service() method
");
pw.print1n(msg);
}
public void destroy() { msg = "This is destroy() method
"; }
+
OeServlet API
* Servlets are the Java programs that run on the Java-enabled web server or
application server.
* They are used to handle the request obtained from the webserver, process the
request, produce the response, then send a response back to the webserver
consists of various interfaces, classes, and methods.
* They are available in the following packages
* javax.serviet
* javax.serviet.http
OSServlet API —javax.serviet
* This package provides the number of interfaces and classes to support Generic
servlet which is protocol independent.
* These interfaces and classes describe and define the contracts between a servlet
class and the runtime environment provided by a servlet container.
OSServlet API -|
GenericServiet Filter
ServletContextAttributeEvent FilterChain
ServletContextEvent FilterConfig
ServletInputStream RequestDispatcher
ServietOutputStream Servlet
ServietRequestAttributeEvent ServletConfig
ServletRequestEvent ServletContext
ServietRequestWrapper ServletContextAttributeListener
ServietResponseWrapper ServletContextListener
ServletRequest
Exception ServletRequestAttributeListener
ServletException ServletRequestListener
UnavailableException ServletResponse
OSServlet API - javax.serviet http
* This package provides the number of interfaces and classes to support HTTP servlet
which is HTTP protocol dependent.
* These interfaces and classes describe and define the contracts between a servlet
class running under HTTP protocol and the runtime environment provided by a
servlet container.
OSServlet API — javax.servlet.http ( Packages )}
HttpServletRequest Interfaces
Cookie
HttpServiet HttpServletResponse
HttpServletRequestWrapper HttpSession
HttpServletResponseWrapper HttpSessionActivationListener
HttpSessionBindingEvent HttpSessionAttributeListener
HttpSessionEvent HttpSessionBindingListener
HttpSessionListener
OSServlet Interface — ( Selvlet API )
* It provides the methods that must be implemented by all the servlets.
* All methods are implemented by the servlet class that extends from a
GenericServiet or HttpServiet class.
* The various methods of the Servlet class are:
® void init(ServletConfig config) throws ServletException
™ ServletConfig getServietConfig()
™ String getServietinfo()
" void service(ServietRequest request, ServietResponse response) throws
ServletException, IOException
void destroy()
OeServlet Interface Example
import javax.servlet.*;
public class DemoServlet implements Servlet {
ServletConfig config=null;
public void init(ServletConfig config) { this.config=config; }
public void service(ServietRequest req,ServletResponse res)
throws IOException,ServietException { }
public void destroy() { System.out.printIn("serviet destroy"); }
public ServletConfig getServletConfig() { return config;}
public String getServletinfo(){ return “This is Servlet interface implementation ex"; }
OeServletConfig Interface ( Servlet API )
* It is implemented by a Web container during the initialization of a servlet to pass the
configuration information to a servlet.
+ It passed to the init()method of the servlet during initialization.
+ It can be used to pass initialization parameters to the servlets.
ServletConfig is an object containing some initial parameters or configuration
information created by Servlet Container and passed to the servlet during initialization.
ServletConfig is for a particular servlet, which means one should store servlet-specific
information in web.xml and retrieve them using this object.
For example, the connection URL can be passed as an initialization parameter of the
servlet.
OSServletConfig Interface Methods — ( Servlet API )
Some of the methods of the ServletConfig interface are:
+ String getinitParameter(String param)
It returns a String object containing the value of the initialization parameters.
+ Enumeration
"+context.getinitParameter(str));ServletRequest Interface — ( Servlet API )
* ServietRequest is used to provide the client request information data to the Servlet as a
content type, a content length, parameter names, and the values, header information
and the attributes.
* Some of the methods of the ServietRequest interface are:
public String getParameter(String paramName)
This method is used to obtain the value of a parameter by its name
public String[] getParameterValues(String paramName)
This methods returns an array of String containing all values of given parameter name.
public Enumeration getParameterNames()
It returns an enumeration for all of the request parameter names
public String getContentType()
Returns the Internet Media Type(IMT) of the requested entity of data, or null if not
known to it
OeServiletResponse Interface — ( Servlet API )
* The ServietResponse interface contains methods that enable a servlet to respond to the
client requests.
+ AServletResponse object is created by the servlet container and passed as an argument
to the servlet’s service function.
* Some of the methods of the ServietResponse interface are:
public ServletOutputStream getOutputStream() throws IOException
This method returns a ServletOutputStream that may be used to write binary data to
the response.
public PrintWriter getWriter() throws IOException
The PrintWriter object is used to transmit character text to the client.
public void setContentType(String type)
Sets the type of the response data
OeHttpServletRequest Interface - Javax.servlet.http — ( Servlet API )
* HttpServietRequest interface extends the ServietRequest interface to provide request
information for HTTP servlets.
+ The servlet container creates an HttpServletRequest object and passes it as an
argument to the servlet's service methods (doGet, doPost, etc).
* The HttpServietRequest breaks a request down into parsed elements, such as request
URI, query arguments and headers. Various get methods allow you to access different
parts of the request. For Example
http://localhost:8080/MyApp/personal/info/top.htm|?info=intro
String uri = request.getRequestURI(); - /MyApp/personal/info/top.htm!
String contextPath = request.getContextPath(); - /MyApp
String servletPath = request.getServietPath(); - /personal
String pathInfo = request.getPathInfo(); - /info/top.html
String queryStr = request.getQueryString(); - info=intro
OeHttpServletResponse Interface - Javax.servlet.http — ( Servlet API )
* The HttpServietResponse interface extends the ServietResponse interface to provide
HTTP-specific functionality in sending a response. For example, it has methods to access
HTTP headers and cookies.
The servlet container creates an HttpServietResponse object and passes it as an
argument to the servlet's service methods (doGet, doPost, etc).
* Some Important Methods of HttpServietResponse.
void addCookie(Cookie cookie)
void sendRedirect(String location)
void setHeader(String name, String value)
String getHeader(String name)
void setStatus(int statuscode)
void getStatus( )
void sendError(int statuscode, String message)
OSRequestDispacher Interface - Javax.servlet — ( Servlet API )
+ It provides the facility of dispatching the request to another resource it may be html,
servlet or jsp.
+ It can also be used to include the content of another resource using RequestDispacher
methods.
+ It is one of the way of servlet collaboration between resources.
* There are two methods defined in the RequestDispatcher interface.
public void forward(ServietRequest request,ServietResponse response) throws
ServietException,java.io.IOException
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file)
on the server.
public void include(ServietRequest request,ServietResponse response) throws
ServletException,java.io.IOException
Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
OeRequestDispacher Interface - Javax.servlet — ( Servlet API )
forward() method
Ces
Fl
Syntax : public RequestDispatcher getRequestDispatcher(String resource)
RequestDispatcher reqdis =request.getRequestDispatcher|"serviet2")
reqdis.forward(request, response);//method may be include or forward
OSRequestDispacher Interface - Javax.servlet — ( Servlet API )
include() method
Meets
Goa
Syntax : public RequestDispatcher getRequestDispatcher(String resource)
RequestDispatcher reqdis =request.getRequestDispatcher|"serviet2")
reqdis.include(request, response);//method may be include or forward
OSSession Tracking
Session is a conversional state between client and server and it can consists of multiple
request and response between client and server.
Http protocol is a stateless in nature so we need to maintain state using session tracking
techniques.
Each time user requests to the server, server treats the request as the new request. So
we need to maintain the state of an user to recognize to particular user.
Servlet API provides Session management through HttpSession interface.
HttpSession allows us to set objects as attributes that can be retrieved in future requests.
You can get session from HttpServietRequest object using following methods.
HttpSession getSession() - This method always returns a HttpSession object. It returns
the session object attached with the request, if the request has no session attached, then
it creates a new session and return it.
HttpSession getSession(boolean flag) - This method returns HttpSession object if request
has session else it returns null.
OeSession Tracking
There are four techniques used in Session Tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4, HttpSession
OSSession Tracking
1. Cookies
* Cookies are small piece of information that is sent by web server in response
header and gets stored in the browser cookies.
When client make further request, it adds the cookie to the request header and
can utilize it to keep track of the session.
Client can maintain a session with cookies but if the client disables the cookies,
then it won’t work.
There are two types of cookies.
* Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the
browser.
* Persistent cookie
It is valid for multiple session . It is not removed each time when user closes
the browser. It is removed only if user logout or signout.
OeSession Tracking
byte”!Session Tracking
2. Hidden Form Field
+ The Server embeds new hidden Fields in every dynamically generated From page
for the client. when the client submits the form to the server the hidden fields
identify the client.
+ Hidden field is an invisible text box of the form page, hidden field value goes to
the server as a request parameter when the form is submitted.
* It always work whether cookie is disabled or not.
Disadvantages:
* The documents need to be embedded the data inside, waste bandwidth.
Need to embed the result from the previous page on the next page.
Everyone can see the embedded data by viewing the original source code.
We cannot store all kinds of java objects in hidden boxes except text/string values.
OeSession Tracking
3. URL Rewriting
* URL rewriting is a process of appending or modifying any url structure while
loading a page.
It will always work whether cookie is disabled or not (browser independent).
* Extra form submission is not required on each pages.
* It works only with Link.
OSSession Tracking
4. HttpSession
* HttpSession interface enables a servlet to read and write the state information
that is associated with an HTTP session.
A session contains information, specific to a particular user across the whole
application. When a user enters into a website for the first time.
Session Management facility creates a unique session ID and typically sends it
back to the browser as a cookie or store in request parameter.
* Each subsequent request from this user passes the cookie containing the session
ID, and the Session Management facility uses this ID to find the user's existing
HttpSession object.
+ HttpSession is obtained via request.getSession().
* The default timeout value is 30 minutes.
OSSession Tracking
The HttpServietRequest interface provides two methods to get the object of HttpSession:
public HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a
session, creates one.
public HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if there is no current
session and create is true, returns a new session.
OSSession Tracking
Commonly used methods of HttpSessi
public String getld()
Returns a string containing the unique identifier value.
public long getCreationTime()
Returns the time when this session was created, measured in milliseconds since midnight
January 1, 1970 GMT.
public long getLastAccessedTime()
Returns the last time the client sent a request associated with this session, as the number of
milliseconds since midnight January 1, 1970 GMT.
public void invalidate()
Invalidates this session then unbinds any objects bound to it.
OeSession Tracking
Commonly used methods of HttpSession interface
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. It replaces the existing
‘one If an attribute already exists.
public Object getAttribute(String name) : Returns the String object specified in the
parameter, from the session object. If no object is found for the specified attribute, then the
getAttribute() method returns null.
public Enumeration getAttributeNames() : Returns an Enumeration that contains the name
of all the objects that are bound as attributes to the session object.
public void removeAttribute(String name) : Removes the given attribute from session.
setMVaxinactivelnterval(int interval) : Sets the session inactivity time in seconds. This is the
time in seconds that specifies how long a sessions remains active since last request received
from client.
Oe