51
CS3002 CS3002 Lecture 10 / Slide Lecture 10 / Slide 1 1 CS3002 Software Technologies Lecture 10

Servlets lecture2

Embed Size (px)

Citation preview

Page 1: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 11

CS3002

Software Technologies

Lecture 10

Page 2: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 22

Agenda

� Error/Exception Handling in Servlets

� Session Tracking in Servlets

� Redirecting, Forwarding and Including Requests in

Servlets

� HTTP Tunneling using Servlets

� JDBC with Servlets

Page 3: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 33

Error Handling

� When a Servlet comes across an Error or Exception, the following things are to be done

� Make sure that it causes minimum harm to the server

� Report to the client

� Log it in a log file for the server administrator

� Reporting to the client can be done using the sendError() method of HttpServletResponse

Page 4: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 44

Error Handling - logging

� The error can also be logged in a log file using the log

method of GenericServlet

� The log file can be found in CATALINA_HOME\logs

� The name of the log file can be specified in server.xml

� Eg:

� Log file :-

� C:\Program Files\Apache Software Foundation\Tomcat

6.0\logs\localhost.<date>.log

� date:-2009-03-12

Page 5: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 55

Configuring Error Pages

� We can configure the web application using web.xml

to customize an error page

� Now, 404.html will be displayed whenever the status

code is 404

<error<error<error<error----page>page>page>page><error<error<error<error----code>code>code>code>

404404404404</error</error</error</error----code>code>code>code><location><location><location><location>

/404.html/404.html/404.html/404.html</location></location></location></location>

</error</error</error</error----page>page>page>page>

Page 6: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 66

Error Handling

� Ex: ErrorHandlingServlet

� ErrorHandlingServletForm.html

� 404.html

Page 7: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 77

Exception Handling

� Any exception that is thrown by the Servlet and not

handled by itself will be handled by its container

� The container handles the exception in a container

specific way

� Servlets that are designed to work on multiple

containers cannot depend on this

� Such Servlets require their own exception handling

techniques

Page 8: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 88

Exception Handling

� However, Servlets can propagate only ServletException,

IOException and unchecked exceptions to the container

because of the way in which the methods are declared

� The service method can throw ServletException and

IOException,

� The init method can throw ServletException

� The destroy method cannot throw any exception

� Any other exception is to be handled by the Servlet itself

Page 9: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 99

ServletException

� If we want the container to handle other exceptions as well, the Servlet may catch the actual exception and throw ServletException in turn

try{try{try{try{//Some statements//Some statements//Some statements//Some statements

}}}}catch(IOExceptioncatch(IOExceptioncatch(IOExceptioncatch(IOException exception){exception){exception){exception){

throw new throw new throw new throw new ServletExceptionServletExceptionServletExceptionServletException();();();();}}}}

Page 10: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1010

ServletException� The class ServletException is having a method

getRootCause() that returns a Throwable object that will

tell the container the root cause of the ServletException

� For example, in the above code snippet, IOException is

the root cause

Page 11: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1111

UnavailableException� A Servlet may be unavailable permanently or temporarily

� Servlets that cannot recover from an error are

permanently unavailable

� Servlets that cannot handle the requests for some time, for

example due to insufficient disk space, can continue

giving service once the administrator has cleared some

disk space

� Such Servlets are temporarily unavailable

� The class UnavailableException which is a sub class of

ServletException will help the programmer to

communicate these to the container

Page 12: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1212

UnavailableException

� The class UnavailableException has two constructors

� The one-argument constructor

UnavailableException(String message) is used to create

a permanent UnavailableException, where message is

the explanation

� The two-argument constructor

UnavailableException(String message, int seconds) is

used to create a temporary UnavailableException,

where message is the explanation and seconds is the

estimated number of seconds, the Servlet is unavailable

Page 13: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1313

UnavailableException� If the unavailable time cannot be estimated, usually a

positive integer is given

� If the Servlet is throwing a permanent

UnavailableException from the init or service method, the

container will try to create a new instance of the Servlet to

handle further requests as the current object will be

permanently unavailable

� If the attempt to create a new instance fails, the client will

get an error message

Page 14: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1414

UnavailableException� If the Servlet is throwing a temporary UnavailableException from

the service method, the container will handle further requests using

SC_SERVICE_UNAVAILABLE (503) status code till the Servlet

is available

� The methods isPermanent() and getUnavailableSeconds() of

UnavailableException can be used by the container to check

whether the Servlet is unavailable permanently and if not, the

duration of unavailability

� If the Servlet is throwing a temporary UnavailableException from

the init method, the container will handle it just like it handles a

permanent UnavailableException by trying to create a new instance

of the Servlet for handling further requests

Page 15: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1515

Configuring Exception Pages

� Just like error pages, we can configure Exception

pages also to generate customized messages

� Now, ExceptionPage.html will be displayed,

whenever ServletException is thrown by the

Servlet

<<<<errorerrorerrorerror----page>page>page>page><exception<exception<exception<exception----type>type>type>type>

javax.servlet.ServletExceptionjavax.servlet.ServletExceptionjavax.servlet.ServletExceptionjavax.servlet.ServletException</exception</exception</exception</exception----type>type>type>type><location><location><location><location>

////ExceptionPage.htmlExceptionPage.htmlExceptionPage.htmlExceptionPage.html</location></location></location></location>

</</</</errorerrorerrorerror----page>page>page>page>

Page 16: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1616

Configuring Exception Pages

� Ex: ExceptionHandlingSerlvet.java

� ExceptionPage.html

Page 17: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1717

Cookies� A cookie is some information the web server sends to the browser

� The browser will accept this information and stores it

� This information can be read back later by the web server

� The class Cookie in the package javax.servlet.http will help to create a cookie

� The class Cookie has a constructor that takes two String objects as parameters – name and value

Cookie c = new Cookie c = new Cookie c = new Cookie c = new Cookie(Cookie(Cookie(Cookie(““““UserNameUserNameUserNameUserName””””, , , , ““““abcabcabcabc””””););););

Page 18: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1818

Cookies� The method addCookie(Cookie) of HttpServletResponsecan be used to add a Cookie

� The method getCookies() of HttpServletRequest will return an array of Cookies that were stored earlier by this domain

� The methods getName() and getValue() of the Cookie class can be used to get the name and value of the Cookie

� The method setMaxAge(int) can be used to specify the maximum age of a Cookie in seconds

� By default, a Cookie will be deleted when the browser is closed

� Any how, some browsers may not support Cookies or want to block Cookies and so this may not work in all cases

Page 19: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 1919

Cookies

� Ex: CookieServlet

� CookieServletForm.html

� Ex:ReadCookieServlet

Page 20: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2020

Sessions

� HTTP is a stateless protocol - All by itself, a request will not tell the server which client is making the request

� In some cases, a Servlet may want to know the specific client that asks for a service

� When a Servlet that takes care of an online shopping site gets a request for adding an item to the shopping cart, it should know which client is asking for the item

� From the time of accessing any one page in the application, till logging out, we may want to know the requests made by a client

� This is called Session Tracking

Page 21: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2121

Session Tracking

� A session starts, whenever a client accesses any one

page in the application

� A session will end, if the client is not responding for a

predefined period of time

� By calling appropriate methods, the programmer can

also end the session when the client logs out

Page 22: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2222

Session Tracking

� In session tracking whenever a client sends a request to the

server then server creates a unique id for that request and sends

back the unique id to the client along with the response object,

now whenever a client sends a request to the server it also sends

a unique id with it so that the server can know from where the

request is coming.

� After the end of a session, if the client accesses a page in the

application again, it will be considered as a new session

� Since the protocol by itself is not tracking the sessions, the web

server has to take care of that

� There are several ways in which a web server can track sessions

Page 23: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2323

Cookies

� Cookies can be used for session tracking

� The server can store some information regarding the

session, like the user name, in a cookie and this can be

used to identify a request from a particular client

� But this technique may not work always, as the client

can disable cookies in her machine

Page 24: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2424

Hidden Fields

� Hidden fields that store some information about a session can be used in the FORM tags

� Since the field is hidden, the user will not see it on the screen

� But when the form is submitted, the server will get this information and can track the session

� The disadvantage is that it will work only for forms

Page 25: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2525

Hidden Fields

� Ex: HiddenFieldServlet

� HiddenFieldServletForm.html

� Ex: WelcomeHiddenFieldServlet

� HelloHiddenFieldServlet

Page 26: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2626

Authentication

� HTTP provides built in authentication support for

taking care of the security issues

� Some resources can be protected with the help of

authentication

� This can be used for session tracking also

� We can configure the server to use Authentication

� So the user will be asked to login with a username and

password

Page 27: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2727

Authentication

� Once the user has logged in, the browser will

automatically send the username and password to all

other pages of the site the user visits

� The user name is available to Servlet through the

method getRemoteUser() of HttpServletRequest

� The Servlet can use this name to track the Session

� But using authentication just for session tracking is not

a good idea

� If we are using authentication to solve some security

issues, we do not have to think about any other session

tracking mechanisms

Page 28: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2828

The HttpSession interface

� Each web server will have an internal mechanism for tracking sessions that would relieve the web application developer from some tasks in session tracking

� Mostly web servers depend on Cookies for session tracking

� Servlet API has an interface called HttpSession, through which a Servlet can communicate with the web server for finding the details of a session

Page 29: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 2929

The HttpSession interface

� HttpSession makes session tracking very easy

� The Servlet programmer need not be bothered about

the internal mechanism used by the web server, as

HttpSession standardizes the way in which Servlet

talks to the web server for session tracking

� The getSession() method of HttpServletRequest will

return HttpSession object for the current session

Page 30: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3030

The HttpSession interface

� The method getID() will return a unique String that

will can be used for identifying a session

� The method setAttribute(String, Object) will help to

store any Object that is represented by a String name as

a session data

� The method getAttribute(String) will return the Object

stored using the setAttribute method

Page 31: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3131

The HttpSession interface

� Ex: SessionTrackingServlet

Page 32: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3232

The HttpSession interface

� The method setMaxInactiveInterval(int) can be used to specify the time in seconds between the client requests before the session is invalidated

� If a negative number is passed to the method setMaxInactiveInterval, the session will never time out

� The method getMaxInactiveInterval() can be used to get the interval set by setMaxInactiveInterval

� The method invalidate() is used to invalidate a session and is usually called when the client logs out

Page 33: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3333

URL Rewriting

� If the server is internally using a Cookie for session tracking, application will not work properly with a browser where Cookies are disabled

� URL rewriting is another way in which we can implement session tracking

� The URL for a page is rewritten to include some information about the session

� Thus some information can be passed to all the pages in an application to track the session

Page 34: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3434

URL Rewriting� The method encodeURL(String url) of

HttpServletResponse will return a re-written URL that

contains some session information also

� For example, encodeURL(HelloWorldServlet) may

return the following string

HelloWorldServlet;jsessionid=86106952376F852D6D206E0

FB87E6571

� The unique value of the attached URLParameter

jsessionid will be used for session tracking

� The disadvantage of URL rewriting is that each URL

should be rewritten

Page 35: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3535

URL Rewriting

� Ex: URLRewritingServletForm.html

� URLRewritingServlet

� Ex: WelcomeURLRewritingServlet

� HelloURLRewritingSerlvet

Page 36: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3636

Redirecting a Request

� A Servlet can redirect a client to use another URL

� This may be done in the following cases

� if the page has moved

� for load balancing

� if the user comes to a wrong page violating a sequence

required by the business logic

� for redirecting the client to a customized error page

Page 37: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3737

Redirecting a Request

� The method sendRedirect(String url) of HttpServletResponse will redirect the

client to the specified URL

� When we want that someone else (other servlet or jsp)should handle the

response of our servlet, then there we should use sendRedirect() method.

� The servlet sends the status code to the browser

� Again the browser makes a new request, but with the name of that servlet

which can now handle the request and the result will be displayed to you by

the browser. The URL will have the address of the new servlet.

� The method encodeRedirectURL(String url) will rewrite the URL to include

the session information also, in case cookies are disabled in the client

� So, the URL that is to be redirected should always pass through the

encodeRedirectURL method

Page 38: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3838

Redirecting a URL

� Ex: Login.html

� SetSessionServlet

� RedirectTestServlet

Page 39: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 3939

Forwarding a Request

� A request can also be forwarded to another URL

� Unlike Redirect, the client will never know about the

redirection

� Ex: ForwardTestServlet

� RequestDispatcher requestDispatcher =

request.getRequestDispatcher("PresentationServlet");

requestDispatcher.forward(request,response);

Page 40: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4040

Forwarding a Request� Forwarding is used when two or more Servlets share

some work

� One Servlet can do some processing, store the result in

an Object and store it as an attribute of the request

object using the setAttribute(String name, Object

object) method of HttpServletRequest

� This Servlet can forward the request to the second

Servlet

� As both of them are using the same request object, the

attribute set by the first Servlet can be retrieved by the

second Servlet using the getAttribute(String name)

method of HttpServletRequest

Page 41: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4141

Forwarding a Request

� Ex: BusinessLogicServletForm.html

� BusinessLogicServlet

� PresentationServlet

Page 42: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4242

Including a Request

� A Servlet can include the output of another Servlet in

its response

� Unlike forward, the calling Servlet retains the control

and can write into the response before and after the

output of the called Servlet

� RequestDispatcher requestDispatcher =

request.getRequestDispatcher("IncludeMeServlet");

requestDispatcher.include(request, response);

Page 43: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4343

Including a Request

� Ex: IncludeTestServlet

� IncludeMeServlet

Page 44: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4444

HTTP Tunneling

� Most of the corporate networks will be protected

behind a firewall

� The client will be able to directly contact only the

firewall

� The firewall will most often block the ftp access

� Usually the only exposed port will be 80 and

acceptable protocol will be HTTP

� This would prevent even a legitimate user from

accessing other services like ftp for transferring data

Page 45: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4545

HTTP Tunneling

� HTTP Tunneling is a technique to overcome this

difficulty

� Transferring bytes of data using the HTTP protocol

through port number 80 is called HTTP Tunneling

� A Servlet can be programmed to read/write bytes of

data from/to the client with the help of Input/Output

Streams

� A Java Object that is Serializable also can be

transferred to the client side using HTTP Tunneling

Page 46: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4646

HTTP Tunneling

� Ex: TunnelServlet

� TunnelServletClient

� Ex: TunnelObjectServlet

� TunnelObjectServletClient

Page 47: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4747

JDBC

� Most of the web applications require a database connection

� Servlets can make JDBC connections and access a database

� Assume a Servlet that should display the names of all customers from the customer table of MySql test database� In which method will you open the connection?

� In which method will you execute the query?

� In which method will you close the connection?

Page 48: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4848

JDBC

� Ex: EmployeeServlet

Page 49: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 4949

Transactions� A simple web application can follow the previous

model

� In some web applications, we may want to do

some atomic transactions

� On success, we want to commit or else rollback

� The model in the previous example will not work

here

try{try{try{try{connection.setAutoCommit(falseconnection.setAutoCommit(falseconnection.setAutoCommit(falseconnection.setAutoCommit(false););););//Transactions//Transactions//Transactions//Transactionsconnection.commitconnection.commitconnection.commitconnection.commit();();();();

}}}}catch(Exceptioncatch(Exceptioncatch(Exceptioncatch(Exception exception){exception){exception){exception){

connection.rollbackconnection.rollbackconnection.rollbackconnection.rollback()()()()}}}}

Page 50: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 5050

Connection Pooling� We require separate Connection objects for each client

which are created, opened, used and closed in the

service method itself

� Since opening a connection for each client is time

consuming, it is better to have a pool of open

connections from which we can pick a free connection

object for each client

� This will increase the performance, as a new

Connection object is not created and opened for each

request, and at the same time, a different Connection

object is available for each client

� This technique is called Connection Pooling

Page 51: Servlets lecture2

CS3002CS3002

Lecture 10 / Slide Lecture 10 / Slide 5151

Summary

� In this module, we have learned the following

� Error/Exception Handling in Servlets

� Session Tracking in Servlets

� Redirecting Forwarding and Including Requests in Servlets

� HTTP Tunneling using Servlets

� JDBC with Servlets