SlideShare a Scribd company logo
Servlet 2.5 & JSP 2.0Haikal magrahi : java/jee
Haikal.magrahi@esprit.tn
Part 1
1
PLAN
1. Why use Servlets & JSPs: an introduction
2. Web App Architecture: high-level overview
3. Being a Servlet: request AND response
4. Being a Web App: attributes and listeners
5. Conversational state: session management
6. Being a JSP: using JSP
7. Script-free pages: scriptless JSP
8. JSTL
9. Keep it secret, keep it safe: web app security
10. The Power of Filters
22
1. Why use Servlets & JSPs: an
introduction


 To build a good web application you need Java , you need JSPs
and Servlets
 JSPs and Servlets allow us to build dynamic web site not like the old
plain static HTML pages
 Servlets are a java code with HTML
 JSP are a HTML with java code
 Thats mean that the servlets are a JSPs
33
2. Web App Architecture
q What’s a container :
 Classes like servlets don’t have a main() they are under the control
of the container ( like tomcat , Jboss, GlassFish…).
 Those classes are deployed in the container so the container who
gives to the servlet the HTTP response and request (we will talk
about this later just keep in mind this ;) ).


44
2. Web App Architecture
q What does the container give you
 Communication support : so you dont have to focus on how your
server will communicates with the client, you dont have to
buildServerSocket, Builduing streams or listen on a port … all of
that make you focus on the business logic of your application.
 Life Cycle management : the container take car of loading,
initializing and instantiating your servlets, invoque their methods
and make her eligible to the GC (garbage collector).
 Multithreading supports : the container creates a new java thread
of any servlets when it recieves a request (you can use the
synchroniziation issues too)
55
2. Web App Architecture
 Declarative security : you use a XML deployment descriptor to
configure, modify secutiry you don’t have to hard code , you
don’t have to touche your java source files or recompilling them.
 JPS support : we will see how cool is a JSP later but if you remember
i said that jsp (HTML+java) = servlet (Java+HTML) the container take
care of translating the JSP into Java code
66
2. Web App Architecture
q How the container handles a requet
1. The User clicks on the page that has a url to the servelt
2. The container find that the request is for a servlet so
He creates 2 objects HttpServletRequest and
HttpServletResponse.
3. The container find the appropriate servlet and creates a new thread of her and
passes to it those two objects
4. The servlet calls the method service() it will calls either one of the methods like
doGet() and doPost() (there are others methods)
5. The method will generate a dynamic page and stuffs it into the response ( the
container always has a reference to the response)
6. The thread terminates the container translate the response object into HTTP
response and sends it to the client and deletes the objects.
77
2. Web App Architecture









 PrintWriter out = response.getWriter(); : you can get a printWriter to write a html text
into the response (there are some option to send a picture for exemple)
88
2. Web App Architecture
q Using deployment descriptor to map URL to Servlets:
 When you deploy your servlet you create a file.xml (DD) tells to the
container how he will run the servlets and JSPs.
 There are 2 elements to map URL into a Servlets :
1. <servlet> : maps internal name to a fully-qualified class name
2. <servlet-mapping> : maps internal name to a public URL name
99
2. Web App Architecture
 Be careful there is a lot you can do with DD
Like security roles, error pages we will see all of
That later just keep in mind what is the DD
1010
2. Web App Architecture
q MVC design pattern
Model* View* Controler* is the separation business logic out of servlet
and put it in a Model a plain old java class
1111
3.Being a Servlet
q Servlet’s life cycle
1. Your servlet class runs his no-args
constructor
2.
3. Calls init() : only once in the servlet’s
life and must finish before container
can call service().
4.
5. Service() : doGet / doPost/… (at least
one of them ). You should not
override it from HttpServlet !!! It will
determines the HTTP method
(GET,POST,…)
q
1212
3.Being a Servlet
q Servlets and Threads
Servlet is always called in its own stack
1. Servlet initialization : (Thread A) the container calls init() after the
servlet instance created and before runs service().
2. client request 1 : (Thread B) the container starts new thread and
invoque service() – after determines the HTTP request method –
it will run the doMethode (doPost) .
3. client request n : (Thread C) the container do the same thinks
new thread -> service() -> doGet
 the Servlet can be instanciate only one time.
1313
3.Being a Servlet
q ServletConfig and ServletContext
What makes an Object become a Servlet :
 A ServletConfig Object : 1 ServletConfig per Servlet, Use it to access
the servlet context , or to pass deploy-time information to the
servlet that you don’t want to make it into it.
servletConfig parameters are configured in the DD
 A ServletContext Object : 1 ServletContext per WebApp. Use it to
acces web parameters or to get server’s informations
v The true job of theses objects is to handle clients request
1414
3.Being a Servlet
q Request and Response
 HttpServletXXXX adds methods
For the HTTP protocol like cookies,
Header, …
 In other word what a servlet uses to
Communicate with the client/server
1515
3.Being a Servlet
q The difference between GET and POST
 POST has a BODY.!
 In fact you both Post and Get can send parameters, but with Get
the data parameters is limited yo what you can stuff into the
request line.
 In the next page you will understand the Post and Get request

1616
3.Being a Servlet 1717
3.Being a Servlet
 But there is other differences like when you use Get request can
bookmarked (end-user can bookmark a request page)
 The probleme with get is that the parameters data shows up in the
browsers input bar (imagine you write a password )
 so besides the size, sercurity and bookmarking you must know when
you use them :
 GET : Hi server, im Get and i need some data just getting things i will
not change anything 0:)
 POST : Hi server, im Post and i has some data to be processed 3:)
(think about update)
1818
3.Being a Servlet
q Idempotent
 Idempotent is good . It means you can do the same thing over and
ver again without any side effect .
For exemple when you hits a buttom and you though he didnt work so
you click again and again until the refresh of page meanwhile the
server process all your hits . Thats not idempotent
 Get is idempotent because there is no update so no side effects
 Post is not idempotent be careful
1919
3.Being a Servlet
q Sending Post or Get request




 To get the parameters String param =
request.getParameter(‘’name of the parameter in the form’’) 
 If the parameter contains lot of values « like checkBox » then String
[] tabParam = request.getParameterValues(’’ ’name of the
parameter in the form’’)
2020
3.Being a Servlet
 Other methods :
 String client =request.getHeader(‘’user’’); client’s platform and
browser info
 Cookie[] cookies = request.getCookies(); cookies associated with
request
 HttpSession session = request.getSession(); session associated with
the client
 String method = request.getMethod(); the http method of the
request
 InputStream input = request.getInputStream(); an input stream from
the request
2121
3.Being a Servlet
q Sending response
 most of time we use response to send data to the client using
getContents() and getWriter() methods after that you simply
doing I/O to write HTML to the stream.
 But we can use the response to send errors, set header and add
coockies … .
2222
3.Being a Servlet
Exemple I/O a jar file
2323
3.Being a Servlet
q Response.setContentType
 To tell the browser what you’are sending back
 He is the same type of MIME type he is http header must included in
the http response
2424
3.Being a Servlet
q Output choices : Characters or Bytes
 Its Plain Old Java.IO gives you only to two Streams :
1.ServletOutputStream for bytes:
2.PrintWriter for characters:
2525
3.Being a Servlet
q Setting and adding response Headers
 setHeader() :Overwrites the existing value
 addHeader() add an additional value
 They both takes name and value
 When you say resp.setContentType(‘’test/html ’’) you setting
header its like you said resp.setHeader(‘’content-
type’’,’’text/html’’);
2626
3.Being a Servlet
q Redirection
Some time you want something else handle the response for your
request
--Sending redirect make the
browser do the work.
q Dispatching
dispatcher the request to other component in your web app ,
The work on the server side
2727
4.Being a Web App
 In this chapter you will make you understand how the pieces of the
web app interact
 We will understand the DD and explore other functionalities.
q Inti parameters
 When you have to put informations that is gonna be change by the
time and you don’t want to have to recompile your servlet code
just to change it, you can initialize it in the DD.
28
4.Being a Web App
 Keep that in mind you can’t use servlet init param until the servlet is
initialized
 Thats mean that you can’t call it in the constructor
 When the container initializes a servlet he makes a unique servlet
config for it
 The container the servlet reads init param only once
 Servlet init param available to only the servlet for which the was
configured.
 You can make a lot of int param
29
4.Being a Web App
 But what if we want to use it with other components like JSP ?
 There is no JSPConfig and ServletConfig only for servlets :’(
 Hmm we have Context init param :D it make param available to
the entire webApp
 In the DD (web.xml):


 In the servlet code :
30
4.Being a Web App
q ServletContext
 Only one servletcontext per application
 Only one servletContext per JVM if we have distributed app
 servletContext it makes the class a real servlet
 Its like a bridge between the components of the webapp and the
container
31
4.Being a Web App
q ServletContextListener
 Listeners make us execute code before serving clients before
execute service().
 We can use it to connect into databases..
 Servlet don’t have main thats why we use listeners
 We can make separate class listen to 2 key events (initialization and
distruction) this class implements
javax.servlet.ServletContextListener
32
4.Being a Web App
 We configure listeners in the DD (web.xml)


 We cannot insert in init param an Object only string , the listeners
help us with these problems we can create the object inside it .
 There are eight listeners

33
4.Being a Web App 34
4.Being a Web App
q Attributes
It’s object you pinned her so the others can get it
3 types:
 Session
 Request
 Application / Context
2 Methods Get and Set
 setAttribute(String name,Object value);
 getAttribute(String name) and dont forget to cast the return type
35
4.Being a Web App
 ContextAttribute isn’t a thread safe
 And this is bad so how we make her thread-safe
 what we Synchronize the service method using Synchronized ?
 This will stop other threads from the same servlet from accessing the
attributre what about the others servlets*
 We need to lock the context not the servlet
36
4.Being a Web App
 to protect SessionAttribute we need to synchronize the session its
not thread safe but imagine that
A client connect with other browser
q SingleTreadModel
 If you implement this interface
You ensures that your servlet
Handle only one request at a time,
 The servlet container can make this guarantee by synchronizing
access to a single instance of the servlet, or by maintaining a
pool of servlet instances and dispatching each new request to a
free servlet ( you don’t need to focus on that a lot)
37
4.Being a Web App
q RequestDispatcher
 RequestDispatcher view = request.getRequestDispatcher(“result.jsp”); :
get a dispatcher for the view JSP
 view.forward(request, response); : to tell to the jdp take over the
request and here are the request and response objects.
 RequestDispater have only 2 methods forward and include
 Getting a RequestDispatcher from a ServletRequest RequestDispatcher
view = request.getRequestDispatcher(“result.jsp”); he will looks in
result.jsp at the same logical location the request is in.
 Getting a RequestDispatcher from a ServletContext must add forward
slash /result.jsp
38
4.Being a Web App
 If you forward a request AFTER a response is sent. The Container will
throw an IllegalStateException.
39
5. Conversational state
q HttpSession
 HttpSession object can hold conversational state across multiple
requests from the same client
 How does the container know who the client is?
 The client must have a unique ID
 On the client’s first request the container generates a unique
session ID
 The client sends back the session ID with each subsequent request
40
5. Conversational state
 The client and container exchange the Session ID is through cookies
 When you write HttpSession s = request.getSession() :
The container will generate an ID he will make a new cookie object
and set her into the response
The same method used for getting session id from the request.
 Session.isNew() returns boolean true if the client has not yet
responded with this session ID.
 Request.getSession(false) : returns a pre-existing session or null if
there was no session associated ith this client
41
5. Conversational state
 You can do sessions even if the client doesn’t accept cookies :
 If the client disable the cookies we can put the ID in the URL
URL+jsessionid=007
 This will work only when the cookies fail or you use the encodeURL
 Response.encodeURL(‘’/servlet.do’’) : extra session ID info to this url
the url encoding is the last hope it means the container will first
check cookies
 If you want to redirect the request to different URL with the same
session uses response.encodeRedirectURL(‘’’’);
42
5. Conversational state
q Session Time out
q
q
q
 We can change timeout of a particular session instance witout
touching the DD


 30 minutes
 Sessions can die by 3 ways : timeOut, call invalidate(),App goes
down
43
5. Conversational state
q Cookies
Ø Cookies is a little piece of data (name/value) exchanged between
the client and the server
Ø We can customize a cookie
Ø Cookie lives as long as a session
Ø
Ø
44
6.Being a JSP
 A JSP is just a Servlet.
 The container translates your JSP into a Servlet.java and compiles it
into servlet.class and loads and initializes it as a servlet object.
 In a jsp you must enter the fully qualified class name like any other
class java, or use import
 <%out.println(pkg1.pk2.Dog.getname()) ; %> or
 <%@ page import = “pkg1.pk2.*” %> ….. <
%out.println(Dog.getName()); %>

45
6.Being a JSP
 To import multiple packages
<%@ page import=“…. , …. , ….”>
 If you see something like that <%@ , it’s a directive
 We can replace out.println with <%= and we remove the ;
 So there are 3 JSP elements types :
Scriptlet : like <% %>
Directive : like <%@ %>
Expression : like <%=> adding sign to scriptlet
46
6.Being a JSP
 Declaring variables in a scriptlet <% int nbProduit = 0 ; %> are
always local variable they will be declared in the service method
when the container translates the JSP to a servlet
 To declate an instance variable or a variable outside the service we
use the JSP elements called declaration <%! Int nbProduit =0; %>

47
6.Being a JSP
q What the container do
Ø Looks at the directives, for information it might need during translation.
Ø Creates an HttpServlet subclass. For Tomcat 5, the generated servlet extends:
org.apache.jasper.runtime.HttpJspBase
Ø If there’s a page directive with an import attribute, it writes the import statements at
the top of the class file, just below the package statement. For Tomcat 5, the
package statement (which you don’t care about) is: package org.apache.jsp;
Ø If there are declarations, it writes them into the class file, usually just below the class
declaration and before the service method. Tomcat 5 declares one static
variable and one instance method of its own.
Ø Builds the service method. The service method’s actual name is _jspService(). It’s
called by the servlet superclass’ overridden service() method, and receives the
HttpServletRequest and HttpServletResponse. As part of building this method, the
Container declares and initializes all the implicit objects.
Ø Combines the plain old HTML (called template text), scriptlets, and expressions into
the service method, formatting everything and writing it to the PrintWriter response
output.
48
6.Being a JSP 49
6.Being a JSP
 To configure a jsp page


 We must also define the url mapping, jsps are like servlets
q Overriding jspInit()
it will be called from the servlet
method init()
50
6.Being a JSP
 JSP makes you use implicit objects to get and set attriibute
corresponding to the four attributes scope.






 JSP allows you to get and set any attribute at any scope with
pageConext implicit object
51
6.Being a JSP
 You can use findAttribute() to find attributes when you don’t know the
scope.
q Three directive
 Page directive <% page import =‘’foo.* ’’ session = ‘’false’’ %>
Defines page-specific properties (content type, character encoding…)
 Taglib directive <% taglibs tagdir=‘’…..’’ %>
Defines tag library to JSP, custom tags …
 Include directive <% include file=‘’img.html’’ %>
lets you build reusable chunks that can be added to each page without
having to duplicate code
52
6.Being a JSP
 Directive page contains lots of attribute like
 import (java.lang, javax.servlet.jsp…)
 isThreadSafe defines whether the generated servlet needs to implement the
singleThreadModel
 contentType for the MIME type
 isELIgnored to tell ‘’ ignore the EL expressions when you translate the page
 isErrorPage to defines wether the current page represents another JSP’s error
page
 errorPage defines a URL to the resource to wich uncaught throwable should
be sent
 The are others like session,language…
53
6.Being a JSP
 To use simple tags that cause java methods to run without having
to put actual java ode into page , we can use EL Expression
Language because using lot of java n our jsp (html it’s a bad
idea)
 EL offer a simpler way to invoke java code
 From <% application.getAttribute(‘’mail’’) %> to $
{applicationScope.mail} with EL
 You can disable scripting by adding in you DD

54
6.Being a JSP
 To ignore EL we add to DD <el-ignored> true </…>

55
7.Script-free pages
 We can use on javaBeans the bean related standard actions
 Without standard action :
<% foo.Dog d = (foo.Dog) request.getAttribute(‘’person’’); %>
<%= p.getName() %>
 With standard actions :
<jsp:useBean id=‘’dog’’ class = ‘’foo.Dog’ scope=‘’request’’ />
<jsp:getProperty name=‘’dog’’ property=‘’name’’ />
56
7.Script-free pages
 Jsp:useBean can create a bean if it dosen’t find one
 You can initilize your object with jsp:setProperty
<jsp:useBean id=‘’dog’’ class=‘’’dog.Dog’ scope=‘’’page’ >
<jsp:setProperty name=‘’’dog’ property=‘’name’’ value=‘’Rita’’ />
<!– this is a body-->
</jsp:useBean>
 The body will run if the bean isn’t found and new one is created
57
7.Script-free pages
q Jsp:useBean and the polymorphic
 The class attribute determines the class of the new object and also
the type of reference variable
 Class =‘’foo.Dog’’ ===> foo.Dog g = new foo.Dog()
 To make polymor we need to add the type
Class = ‘’foo.Dog’’ type=‘’foo.Animal’’ ===> Animal a = new Dog();
 If type used without class the bean must already exist
58
7.Script-free pages
 Param attribute lets you set value of a property to the value of a
request parameter just by naming the request parameter




 Bean tags convert primitive properties automatically for exemple it
takes a string request parameter and converts it to an int
 Automatic string-to-primitive conversion does not work if you use
scripting

59
7.Script-free pages
 In the property you can’t say dog.name !
 So if you want to call the name of d dog object you must uses EL
without scripting
${dog.name} : the first variable is either an implicit object or an
attribute
 Implicit object are not like jsp scripting (param, pageScope )except
pageConext all implicit objects are a map objects except
pageContext too
 The second variable is a map key or a bean property
 We can change the dot with [‘’name’’] it’s a good way when the
dog is an array or a list
60
7.Script-free pages






 If you don’t use the brackets its like you tell the container go find an
attribute named X use the Value of that attribute as the key into
the map or return null.
61
7.Script-free pages
q Implicit object
 Param implicit object is fine when you have only one parameter for
that particular parameter name else use paramValues $
{param.name} , ${paramValues.name[“0”]}
 Header implicit object to get the server host information $
{header.host} or ${header[‘’host’’]}
 requestScope is not the request object so if you want to call your
request object use the page context $
{pageContext.request.method}
+ the request Scope useful because it lets you switch to the [}
operator,that can take String names that don’t conform to JNR java
naming rules
62
7.Script-free pages
 Cookies imp object now we can call a specific cookie without any
hard code ${cookie.userName.Value}
 Context init parameter imp object with scriptiong <%=
application.getInitParameter(“mail1”) %> and with EL $
{initParam.mainEmail}
63
7.Script-free pages
q EL functions
 We use EL functions when we want to call methods without
scripting using TLD (the tag library Descriptor ) we create this file
and it contains the tag <function> </function> for oour method
 EL is null-friendly even if we had a null value and it can’t find an
attribute it treats the null value as ZERO in aruthmetic and FALSE
for logicl expressions



64
7.Script-free pages
q Reusable template pieces
 When we uses directives like include its like we tell the container
insert the header of the page x into this page
v The include Directive
Ø <%@ include file =‘’headerof the page x.jsp’’%> : a copy
Ø <js:include page =‘’….jsp’’ /> : insert the response of ….jsp
Ø The include directive happens at translation time
Ø The include standard happens at runtime

65
7.Script-free pages
 If you want to forward your client from a jsp to another uses
<jsp:forward page =‘’other.jsp’’/>

66
8.JSTL
 Looping with jstl
<c:forEach var=‘’movie’’ items =‘’….’’></forEach>
 Conditional include with
<c:if test=‘’${userName eq ‘haikal’ }’’> </c:if> without if
 <c:choose> if you have else u can do this jstl tags
<c:when test=‘’’’></c:when>
<c:otherwise></c:otherwise>
</c:choose>

67
8.JSTL
 <c:set var=‘’nomeDog’’ scope=‘’session ’’ value =‘’spike’’/> : the
value doesn’t have to be string
 <c:set target=‘’${PetMap}’’ property =‘’dogName’’
value=‘’clover’’ />c : the target must not be null
 Property is like if targer is a bean set the value of the prerty
dogname if it’s a map set the value of a key named dogName
 You can’t do value + var only one of them
 <c:remove> to remove from session
68
8.JSTL
 <c:import url=‘’’’/> adds the content from the value of the url attribute to the
current page, the import can reach outside the web app unlike the import
q Make our own error pages
<%@ page isErrorPage=‘’true’’%>
<%@ page errorPage=‘errorpage.jjsp’’%> if somthing goes wrong forward the
request to errorpage.jsp
 We can use <error-page> dd tag for type exception or http errors
 In your DD add <error-page>*
<exception-type>java.lang.Throwable</exception-type> or <error-
code>404</error-code>
<location>/errorpage.jsp</location>
</error-page>
q
69
8.JSTL
 To handle an exception use <c:catch> like try/catch </c:atch>
 Add var=‘’myExceeption’’ to assign the exception to it
70
8.JSTL 71
9. Keep it secret, keep it safe: web
app security
 Here we will talk about the security authentifcation authorization ,
confidentiality and data integrity
 The container contains a security table if the URL in it that means
that the resource is constrained
 The container will supply a vendor-specific table containing
usernames and their pswd
 You can add user in the realm (where the authentication
information is stored) in tomcat it calls tomcat-users.xml

72
9. Keep it secret, keep it safe: web
app security
 <role rolename=‘’guest’’ / >
<role rolename=‘’Membre’’/>
<user username=‘’haikal’’ password=‘’haikal’’ roles =‘’member,
guest’’ /> becareful this is a part of vendor specific not DD
 To get the container to ask for a username and pswd we must add
in the DD <login-config><auth-method>BASIC</auth-
method></login-config>

73
9. Keep it secret, keep it safe: web
app security
 Authorization step 1 :
Add security role iin the DD to map its vendor spec role information
with role name in our DD
<security-role><role-name>guest</role-name></security-role>
 Step 2 :
Defining resource/method constraints using in you DD
<security-constrain>
<web-resource-collection>
<web-resource-name>UpdateDog</web-resource-name>
74
9. Keep it secret, keep it safe: web
app security
<url-pattern>/a/*</url-pattern> : element define the resources to be
contrained
<http-method>GET</http-method> the http method which it’s
constrained
</web-resoirce-collection>
<auth-constraint>
<role-name>Admin</role-name> who is allowed to do the http
method constsrained
</auth-constraint>
75
9. Keep it secret, keep it safe: web
app security
We match up roles in the DD with roles in a servlet when we call for
example if request.isUserInRole(‘’ ’guest’’ )==true, before this method is
called the user needs to be authentificated
q The 4 auth-mehod:
 Basic = transmits the login information not encrypted
 DIGEST = secure way but there are containers does not support the
encryption mechanism
 CLIENT-CERT = secure form using public key but my clients must
have a certificate before they can login to my system
 FORM = allows me to custom login form but the username and
psswd are send back in http request with no encryption
76
9. Keep it secret, keep it safe: web
app security
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/loginPage.html</form-login-page>
<form-error-page>/loginError.html</form-error-page>
</form-login-config>
</login-config>
77
9. Keep it secret, keep it safe: web
app security
q Protecting transport layer connection
Ø Ssecuring the http over TCP (SSL)
Ø Adds in the <security-constraint> <user-data-guarantee>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-guarantee> </security-constraint> if you write <auth-
constraint> and </web-resource-collection> this mean only x can
make a POST/GET… request to the resource yyy and make t secure
Ø
78
9. Keep it secret, keep it safe: web
app security
 Remember that <security-constraint> is about what happens after
the request
 Thus , we need to protect the data coming in from a request thats
why we uses confidental to change the protocol http to https

79
9. The Power Filters
 Sometimes you want to keep track of system’s response times
across all of its different user interactions.
 Filters are java components similar to servlets
 Intercept and process requet before they are sent to the servlet
 And before the response goes back to the client
80
9. The Power Filters
 Filters doesn’t care which filters ran before it did or next
 The DD controls the order in wich filters run
 In the DD you can link the firlts by telling the container for these url
run filtre x then filtre a … then run my servlet
 Of course we can delete one or swap it
 Why the filters like servlets :
The container knows their API by implementing the Filter interface
He manages their lifecycle (they have init() , destroy(), doPost()/Get
+doFiltre()
They’re declared in the DD
81
9. The Power Filters 82
9. The Power Filters
 Every filtre must implements init and do filter and destroy
 The doFilter( is called every time the container determines that the
filter should be applied to the current request
q Declaring and ordering filters

83
9. The Power Filters
 <init-param> is optional and we can have many
 <servlet-name> element defines which single web app resource will
use this filter
 Filters can be applied to request dispatchers too
84
9. The Power Filters
 We cannot filtre the response because it’s too late the out put
goes straight from the servlet back to the client
 But we can swap our real response object with a custom response
(wrapper classes) when we passing him to the servlet

 Whenever you want to create a custom request or response object,
just subclass one of the convenience request or response
“wrapper” classes. A wrapper wraps the REAL request or
response object, and delegates (passes through) calls to the real
thing, while still letting you do the extra things you need for your
custom request or response.
85
9. The Power Filters
 ServletRequestWrapper
 HttpServletRequestWrapper
 ServletResponseWrapper
 HttpServletResponseWrapper
 public void doFilter( request, response, chain)
{ CompressionResponseWrapper wrappedResp = new
CompressionResponseWrapper(response);
chain.doFilter(request, wrappedResp);
}
86

More Related Content

What's hot

Java servlets
Java servletsJava servlets
Java servlets
lopjuan
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
Raghu nath
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 

What's hot (20)

Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Java servlets
Java servletsJava servlets
Java servlets
 
Servlets
ServletsServlets
Servlets
 
JDBC
JDBCJDBC
JDBC
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Servlet lifecycle
Servlet lifecycleServlet lifecycle
Servlet lifecycle
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servlets
ServletsServlets
Servlets
 
Java server pages
Java server pagesJava server pages
Java server pages
 

Similar to servlet 2.5 & JSP 2.0

Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
elliando dias
 

Similar to servlet 2.5 & JSP 2.0 (20)

Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Online grocery store
Online grocery storeOnline grocery store
Online grocery store
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
Major project report
Major project reportMajor project report
Major project report
 

Recently uploaded

Recently uploaded (20)

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 

servlet 2.5 & JSP 2.0

  • 1. Servlet 2.5 & JSP 2.0Haikal magrahi : java/jee Haikal.magrahi@esprit.tn Part 1 1
  • 2. PLAN 1. Why use Servlets & JSPs: an introduction 2. Web App Architecture: high-level overview 3. Being a Servlet: request AND response 4. Being a Web App: attributes and listeners 5. Conversational state: session management 6. Being a JSP: using JSP 7. Script-free pages: scriptless JSP 8. JSTL 9. Keep it secret, keep it safe: web app security 10. The Power of Filters 22
  • 3. 1. Why use Servlets & JSPs: an introduction    To build a good web application you need Java , you need JSPs and Servlets  JSPs and Servlets allow us to build dynamic web site not like the old plain static HTML pages  Servlets are a java code with HTML  JSP are a HTML with java code  Thats mean that the servlets are a JSPs 33
  • 4. 2. Web App Architecture q What’s a container :  Classes like servlets don’t have a main() they are under the control of the container ( like tomcat , Jboss, GlassFish…).  Those classes are deployed in the container so the container who gives to the servlet the HTTP response and request (we will talk about this later just keep in mind this ;) ).   44
  • 5. 2. Web App Architecture q What does the container give you  Communication support : so you dont have to focus on how your server will communicates with the client, you dont have to buildServerSocket, Builduing streams or listen on a port … all of that make you focus on the business logic of your application.  Life Cycle management : the container take car of loading, initializing and instantiating your servlets, invoque their methods and make her eligible to the GC (garbage collector).  Multithreading supports : the container creates a new java thread of any servlets when it recieves a request (you can use the synchroniziation issues too) 55
  • 6. 2. Web App Architecture  Declarative security : you use a XML deployment descriptor to configure, modify secutiry you don’t have to hard code , you don’t have to touche your java source files or recompilling them.  JPS support : we will see how cool is a JSP later but if you remember i said that jsp (HTML+java) = servlet (Java+HTML) the container take care of translating the JSP into Java code 66
  • 7. 2. Web App Architecture q How the container handles a requet 1. The User clicks on the page that has a url to the servelt 2. The container find that the request is for a servlet so He creates 2 objects HttpServletRequest and HttpServletResponse. 3. The container find the appropriate servlet and creates a new thread of her and passes to it those two objects 4. The servlet calls the method service() it will calls either one of the methods like doGet() and doPost() (there are others methods) 5. The method will generate a dynamic page and stuffs it into the response ( the container always has a reference to the response) 6. The thread terminates the container translate the response object into HTTP response and sends it to the client and deletes the objects. 77
  • 8. 2. Web App Architecture           PrintWriter out = response.getWriter(); : you can get a printWriter to write a html text into the response (there are some option to send a picture for exemple) 88
  • 9. 2. Web App Architecture q Using deployment descriptor to map URL to Servlets:  When you deploy your servlet you create a file.xml (DD) tells to the container how he will run the servlets and JSPs.  There are 2 elements to map URL into a Servlets : 1. <servlet> : maps internal name to a fully-qualified class name 2. <servlet-mapping> : maps internal name to a public URL name 99
  • 10. 2. Web App Architecture  Be careful there is a lot you can do with DD Like security roles, error pages we will see all of That later just keep in mind what is the DD 1010
  • 11. 2. Web App Architecture q MVC design pattern Model* View* Controler* is the separation business logic out of servlet and put it in a Model a plain old java class 1111
  • 12. 3.Being a Servlet q Servlet’s life cycle 1. Your servlet class runs his no-args constructor 2. 3. Calls init() : only once in the servlet’s life and must finish before container can call service(). 4. 5. Service() : doGet / doPost/… (at least one of them ). You should not override it from HttpServlet !!! It will determines the HTTP method (GET,POST,…) q 1212
  • 13. 3.Being a Servlet q Servlets and Threads Servlet is always called in its own stack 1. Servlet initialization : (Thread A) the container calls init() after the servlet instance created and before runs service(). 2. client request 1 : (Thread B) the container starts new thread and invoque service() – after determines the HTTP request method – it will run the doMethode (doPost) . 3. client request n : (Thread C) the container do the same thinks new thread -> service() -> doGet  the Servlet can be instanciate only one time. 1313
  • 14. 3.Being a Servlet q ServletConfig and ServletContext What makes an Object become a Servlet :  A ServletConfig Object : 1 ServletConfig per Servlet, Use it to access the servlet context , or to pass deploy-time information to the servlet that you don’t want to make it into it. servletConfig parameters are configured in the DD  A ServletContext Object : 1 ServletContext per WebApp. Use it to acces web parameters or to get server’s informations v The true job of theses objects is to handle clients request 1414
  • 15. 3.Being a Servlet q Request and Response  HttpServletXXXX adds methods For the HTTP protocol like cookies, Header, …  In other word what a servlet uses to Communicate with the client/server 1515
  • 16. 3.Being a Servlet q The difference between GET and POST  POST has a BODY.!  In fact you both Post and Get can send parameters, but with Get the data parameters is limited yo what you can stuff into the request line.  In the next page you will understand the Post and Get request  1616
  • 18. 3.Being a Servlet  But there is other differences like when you use Get request can bookmarked (end-user can bookmark a request page)  The probleme with get is that the parameters data shows up in the browsers input bar (imagine you write a password )  so besides the size, sercurity and bookmarking you must know when you use them :  GET : Hi server, im Get and i need some data just getting things i will not change anything 0:)  POST : Hi server, im Post and i has some data to be processed 3:) (think about update) 1818
  • 19. 3.Being a Servlet q Idempotent  Idempotent is good . It means you can do the same thing over and ver again without any side effect . For exemple when you hits a buttom and you though he didnt work so you click again and again until the refresh of page meanwhile the server process all your hits . Thats not idempotent  Get is idempotent because there is no update so no side effects  Post is not idempotent be careful 1919
  • 20. 3.Being a Servlet q Sending Post or Get request      To get the parameters String param = request.getParameter(‘’name of the parameter in the form’’)   If the parameter contains lot of values « like checkBox » then String [] tabParam = request.getParameterValues(’’ ’name of the parameter in the form’’) 2020
  • 21. 3.Being a Servlet  Other methods :  String client =request.getHeader(‘’user’’); client’s platform and browser info  Cookie[] cookies = request.getCookies(); cookies associated with request  HttpSession session = request.getSession(); session associated with the client  String method = request.getMethod(); the http method of the request  InputStream input = request.getInputStream(); an input stream from the request 2121
  • 22. 3.Being a Servlet q Sending response  most of time we use response to send data to the client using getContents() and getWriter() methods after that you simply doing I/O to write HTML to the stream.  But we can use the response to send errors, set header and add coockies … . 2222
  • 23. 3.Being a Servlet Exemple I/O a jar file 2323
  • 24. 3.Being a Servlet q Response.setContentType  To tell the browser what you’are sending back  He is the same type of MIME type he is http header must included in the http response 2424
  • 25. 3.Being a Servlet q Output choices : Characters or Bytes  Its Plain Old Java.IO gives you only to two Streams : 1.ServletOutputStream for bytes: 2.PrintWriter for characters: 2525
  • 26. 3.Being a Servlet q Setting and adding response Headers  setHeader() :Overwrites the existing value  addHeader() add an additional value  They both takes name and value  When you say resp.setContentType(‘’test/html ’’) you setting header its like you said resp.setHeader(‘’content- type’’,’’text/html’’); 2626
  • 27. 3.Being a Servlet q Redirection Some time you want something else handle the response for your request --Sending redirect make the browser do the work. q Dispatching dispatcher the request to other component in your web app , The work on the server side 2727
  • 28. 4.Being a Web App  In this chapter you will make you understand how the pieces of the web app interact  We will understand the DD and explore other functionalities. q Inti parameters  When you have to put informations that is gonna be change by the time and you don’t want to have to recompile your servlet code just to change it, you can initialize it in the DD. 28
  • 29. 4.Being a Web App  Keep that in mind you can’t use servlet init param until the servlet is initialized  Thats mean that you can’t call it in the constructor  When the container initializes a servlet he makes a unique servlet config for it  The container the servlet reads init param only once  Servlet init param available to only the servlet for which the was configured.  You can make a lot of int param 29
  • 30. 4.Being a Web App  But what if we want to use it with other components like JSP ?  There is no JSPConfig and ServletConfig only for servlets :’(  Hmm we have Context init param :D it make param available to the entire webApp  In the DD (web.xml):    In the servlet code : 30
  • 31. 4.Being a Web App q ServletContext  Only one servletcontext per application  Only one servletContext per JVM if we have distributed app  servletContext it makes the class a real servlet  Its like a bridge between the components of the webapp and the container 31
  • 32. 4.Being a Web App q ServletContextListener  Listeners make us execute code before serving clients before execute service().  We can use it to connect into databases..  Servlet don’t have main thats why we use listeners  We can make separate class listen to 2 key events (initialization and distruction) this class implements javax.servlet.ServletContextListener 32
  • 33. 4.Being a Web App  We configure listeners in the DD (web.xml)    We cannot insert in init param an Object only string , the listeners help us with these problems we can create the object inside it .  There are eight listeners  33
  • 34. 4.Being a Web App 34
  • 35. 4.Being a Web App q Attributes It’s object you pinned her so the others can get it 3 types:  Session  Request  Application / Context 2 Methods Get and Set  setAttribute(String name,Object value);  getAttribute(String name) and dont forget to cast the return type 35
  • 36. 4.Being a Web App  ContextAttribute isn’t a thread safe  And this is bad so how we make her thread-safe  what we Synchronize the service method using Synchronized ?  This will stop other threads from the same servlet from accessing the attributre what about the others servlets*  We need to lock the context not the servlet 36
  • 37. 4.Being a Web App  to protect SessionAttribute we need to synchronize the session its not thread safe but imagine that A client connect with other browser q SingleTreadModel  If you implement this interface You ensures that your servlet Handle only one request at a time,  The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet ( you don’t need to focus on that a lot) 37
  • 38. 4.Being a Web App q RequestDispatcher  RequestDispatcher view = request.getRequestDispatcher(“result.jsp”); : get a dispatcher for the view JSP  view.forward(request, response); : to tell to the jdp take over the request and here are the request and response objects.  RequestDispater have only 2 methods forward and include  Getting a RequestDispatcher from a ServletRequest RequestDispatcher view = request.getRequestDispatcher(“result.jsp”); he will looks in result.jsp at the same logical location the request is in.  Getting a RequestDispatcher from a ServletContext must add forward slash /result.jsp 38
  • 39. 4.Being a Web App  If you forward a request AFTER a response is sent. The Container will throw an IllegalStateException. 39
  • 40. 5. Conversational state q HttpSession  HttpSession object can hold conversational state across multiple requests from the same client  How does the container know who the client is?  The client must have a unique ID  On the client’s first request the container generates a unique session ID  The client sends back the session ID with each subsequent request 40
  • 41. 5. Conversational state  The client and container exchange the Session ID is through cookies  When you write HttpSession s = request.getSession() : The container will generate an ID he will make a new cookie object and set her into the response The same method used for getting session id from the request.  Session.isNew() returns boolean true if the client has not yet responded with this session ID.  Request.getSession(false) : returns a pre-existing session or null if there was no session associated ith this client 41
  • 42. 5. Conversational state  You can do sessions even if the client doesn’t accept cookies :  If the client disable the cookies we can put the ID in the URL URL+jsessionid=007  This will work only when the cookies fail or you use the encodeURL  Response.encodeURL(‘’/servlet.do’’) : extra session ID info to this url the url encoding is the last hope it means the container will first check cookies  If you want to redirect the request to different URL with the same session uses response.encodeRedirectURL(‘’’’); 42
  • 43. 5. Conversational state q Session Time out q q q  We can change timeout of a particular session instance witout touching the DD    30 minutes  Sessions can die by 3 ways : timeOut, call invalidate(),App goes down 43
  • 44. 5. Conversational state q Cookies Ø Cookies is a little piece of data (name/value) exchanged between the client and the server Ø We can customize a cookie Ø Cookie lives as long as a session Ø Ø 44
  • 45. 6.Being a JSP  A JSP is just a Servlet.  The container translates your JSP into a Servlet.java and compiles it into servlet.class and loads and initializes it as a servlet object.  In a jsp you must enter the fully qualified class name like any other class java, or use import  <%out.println(pkg1.pk2.Dog.getname()) ; %> or  <%@ page import = “pkg1.pk2.*” %> ….. < %out.println(Dog.getName()); %>  45
  • 46. 6.Being a JSP  To import multiple packages <%@ page import=“…. , …. , ….”>  If you see something like that <%@ , it’s a directive  We can replace out.println with <%= and we remove the ;  So there are 3 JSP elements types : Scriptlet : like <% %> Directive : like <%@ %> Expression : like <%=> adding sign to scriptlet 46
  • 47. 6.Being a JSP  Declaring variables in a scriptlet <% int nbProduit = 0 ; %> are always local variable they will be declared in the service method when the container translates the JSP to a servlet  To declate an instance variable or a variable outside the service we use the JSP elements called declaration <%! Int nbProduit =0; %>  47
  • 48. 6.Being a JSP q What the container do Ø Looks at the directives, for information it might need during translation. Ø Creates an HttpServlet subclass. For Tomcat 5, the generated servlet extends: org.apache.jasper.runtime.HttpJspBase Ø If there’s a page directive with an import attribute, it writes the import statements at the top of the class file, just below the package statement. For Tomcat 5, the package statement (which you don’t care about) is: package org.apache.jsp; Ø If there are declarations, it writes them into the class file, usually just below the class declaration and before the service method. Tomcat 5 declares one static variable and one instance method of its own. Ø Builds the service method. The service method’s actual name is _jspService(). It’s called by the servlet superclass’ overridden service() method, and receives the HttpServletRequest and HttpServletResponse. As part of building this method, the Container declares and initializes all the implicit objects. Ø Combines the plain old HTML (called template text), scriptlets, and expressions into the service method, formatting everything and writing it to the PrintWriter response output. 48
  • 50. 6.Being a JSP  To configure a jsp page    We must also define the url mapping, jsps are like servlets q Overriding jspInit() it will be called from the servlet method init() 50
  • 51. 6.Being a JSP  JSP makes you use implicit objects to get and set attriibute corresponding to the four attributes scope.        JSP allows you to get and set any attribute at any scope with pageConext implicit object 51
  • 52. 6.Being a JSP  You can use findAttribute() to find attributes when you don’t know the scope. q Three directive  Page directive <% page import =‘’foo.* ’’ session = ‘’false’’ %> Defines page-specific properties (content type, character encoding…)  Taglib directive <% taglibs tagdir=‘’…..’’ %> Defines tag library to JSP, custom tags …  Include directive <% include file=‘’img.html’’ %> lets you build reusable chunks that can be added to each page without having to duplicate code 52
  • 53. 6.Being a JSP  Directive page contains lots of attribute like  import (java.lang, javax.servlet.jsp…)  isThreadSafe defines whether the generated servlet needs to implement the singleThreadModel  contentType for the MIME type  isELIgnored to tell ‘’ ignore the EL expressions when you translate the page  isErrorPage to defines wether the current page represents another JSP’s error page  errorPage defines a URL to the resource to wich uncaught throwable should be sent  The are others like session,language… 53
  • 54. 6.Being a JSP  To use simple tags that cause java methods to run without having to put actual java ode into page , we can use EL Expression Language because using lot of java n our jsp (html it’s a bad idea)  EL offer a simpler way to invoke java code  From <% application.getAttribute(‘’mail’’) %> to $ {applicationScope.mail} with EL  You can disable scripting by adding in you DD  54
  • 55. 6.Being a JSP  To ignore EL we add to DD <el-ignored> true </…>  55
  • 56. 7.Script-free pages  We can use on javaBeans the bean related standard actions  Without standard action : <% foo.Dog d = (foo.Dog) request.getAttribute(‘’person’’); %> <%= p.getName() %>  With standard actions : <jsp:useBean id=‘’dog’’ class = ‘’foo.Dog’ scope=‘’request’’ /> <jsp:getProperty name=‘’dog’’ property=‘’name’’ /> 56
  • 57. 7.Script-free pages  Jsp:useBean can create a bean if it dosen’t find one  You can initilize your object with jsp:setProperty <jsp:useBean id=‘’dog’’ class=‘’’dog.Dog’ scope=‘’’page’ > <jsp:setProperty name=‘’’dog’ property=‘’name’’ value=‘’Rita’’ /> <!– this is a body--> </jsp:useBean>  The body will run if the bean isn’t found and new one is created 57
  • 58. 7.Script-free pages q Jsp:useBean and the polymorphic  The class attribute determines the class of the new object and also the type of reference variable  Class =‘’foo.Dog’’ ===> foo.Dog g = new foo.Dog()  To make polymor we need to add the type Class = ‘’foo.Dog’’ type=‘’foo.Animal’’ ===> Animal a = new Dog();  If type used without class the bean must already exist 58
  • 59. 7.Script-free pages  Param attribute lets you set value of a property to the value of a request parameter just by naming the request parameter      Bean tags convert primitive properties automatically for exemple it takes a string request parameter and converts it to an int  Automatic string-to-primitive conversion does not work if you use scripting  59
  • 60. 7.Script-free pages  In the property you can’t say dog.name !  So if you want to call the name of d dog object you must uses EL without scripting ${dog.name} : the first variable is either an implicit object or an attribute  Implicit object are not like jsp scripting (param, pageScope )except pageConext all implicit objects are a map objects except pageContext too  The second variable is a map key or a bean property  We can change the dot with [‘’name’’] it’s a good way when the dog is an array or a list 60
  • 61. 7.Script-free pages        If you don’t use the brackets its like you tell the container go find an attribute named X use the Value of that attribute as the key into the map or return null. 61
  • 62. 7.Script-free pages q Implicit object  Param implicit object is fine when you have only one parameter for that particular parameter name else use paramValues $ {param.name} , ${paramValues.name[“0”]}  Header implicit object to get the server host information $ {header.host} or ${header[‘’host’’]}  requestScope is not the request object so if you want to call your request object use the page context $ {pageContext.request.method} + the request Scope useful because it lets you switch to the [} operator,that can take String names that don’t conform to JNR java naming rules 62
  • 63. 7.Script-free pages  Cookies imp object now we can call a specific cookie without any hard code ${cookie.userName.Value}  Context init parameter imp object with scriptiong <%= application.getInitParameter(“mail1”) %> and with EL $ {initParam.mainEmail} 63
  • 64. 7.Script-free pages q EL functions  We use EL functions when we want to call methods without scripting using TLD (the tag library Descriptor ) we create this file and it contains the tag <function> </function> for oour method  EL is null-friendly even if we had a null value and it can’t find an attribute it treats the null value as ZERO in aruthmetic and FALSE for logicl expressions    64
  • 65. 7.Script-free pages q Reusable template pieces  When we uses directives like include its like we tell the container insert the header of the page x into this page v The include Directive Ø <%@ include file =‘’headerof the page x.jsp’’%> : a copy Ø <js:include page =‘’….jsp’’ /> : insert the response of ….jsp Ø The include directive happens at translation time Ø The include standard happens at runtime  65
  • 66. 7.Script-free pages  If you want to forward your client from a jsp to another uses <jsp:forward page =‘’other.jsp’’/>  66
  • 67. 8.JSTL  Looping with jstl <c:forEach var=‘’movie’’ items =‘’….’’></forEach>  Conditional include with <c:if test=‘’${userName eq ‘haikal’ }’’> </c:if> without if  <c:choose> if you have else u can do this jstl tags <c:when test=‘’’’></c:when> <c:otherwise></c:otherwise> </c:choose>  67
  • 68. 8.JSTL  <c:set var=‘’nomeDog’’ scope=‘’session ’’ value =‘’spike’’/> : the value doesn’t have to be string  <c:set target=‘’${PetMap}’’ property =‘’dogName’’ value=‘’clover’’ />c : the target must not be null  Property is like if targer is a bean set the value of the prerty dogname if it’s a map set the value of a key named dogName  You can’t do value + var only one of them  <c:remove> to remove from session 68
  • 69. 8.JSTL  <c:import url=‘’’’/> adds the content from the value of the url attribute to the current page, the import can reach outside the web app unlike the import q Make our own error pages <%@ page isErrorPage=‘’true’’%> <%@ page errorPage=‘errorpage.jjsp’’%> if somthing goes wrong forward the request to errorpage.jsp  We can use <error-page> dd tag for type exception or http errors  In your DD add <error-page>* <exception-type>java.lang.Throwable</exception-type> or <error- code>404</error-code> <location>/errorpage.jsp</location> </error-page> q 69
  • 70. 8.JSTL  To handle an exception use <c:catch> like try/catch </c:atch>  Add var=‘’myExceeption’’ to assign the exception to it 70
  • 72. 9. Keep it secret, keep it safe: web app security  Here we will talk about the security authentifcation authorization , confidentiality and data integrity  The container contains a security table if the URL in it that means that the resource is constrained  The container will supply a vendor-specific table containing usernames and their pswd  You can add user in the realm (where the authentication information is stored) in tomcat it calls tomcat-users.xml  72
  • 73. 9. Keep it secret, keep it safe: web app security  <role rolename=‘’guest’’ / > <role rolename=‘’Membre’’/> <user username=‘’haikal’’ password=‘’haikal’’ roles =‘’member, guest’’ /> becareful this is a part of vendor specific not DD  To get the container to ask for a username and pswd we must add in the DD <login-config><auth-method>BASIC</auth- method></login-config>  73
  • 74. 9. Keep it secret, keep it safe: web app security  Authorization step 1 : Add security role iin the DD to map its vendor spec role information with role name in our DD <security-role><role-name>guest</role-name></security-role>  Step 2 : Defining resource/method constraints using in you DD <security-constrain> <web-resource-collection> <web-resource-name>UpdateDog</web-resource-name> 74
  • 75. 9. Keep it secret, keep it safe: web app security <url-pattern>/a/*</url-pattern> : element define the resources to be contrained <http-method>GET</http-method> the http method which it’s constrained </web-resoirce-collection> <auth-constraint> <role-name>Admin</role-name> who is allowed to do the http method constsrained </auth-constraint> 75
  • 76. 9. Keep it secret, keep it safe: web app security We match up roles in the DD with roles in a servlet when we call for example if request.isUserInRole(‘’ ’guest’’ )==true, before this method is called the user needs to be authentificated q The 4 auth-mehod:  Basic = transmits the login information not encrypted  DIGEST = secure way but there are containers does not support the encryption mechanism  CLIENT-CERT = secure form using public key but my clients must have a certificate before they can login to my system  FORM = allows me to custom login form but the username and psswd are send back in http request with no encryption 76
  • 77. 9. Keep it secret, keep it safe: web app security <login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/loginPage.html</form-login-page> <form-error-page>/loginError.html</form-error-page> </form-login-config> </login-config> 77
  • 78. 9. Keep it secret, keep it safe: web app security q Protecting transport layer connection Ø Ssecuring the http over TCP (SSL) Ø Adds in the <security-constraint> <user-data-guarantee> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-guarantee> </security-constraint> if you write <auth- constraint> and </web-resource-collection> this mean only x can make a POST/GET… request to the resource yyy and make t secure Ø 78
  • 79. 9. Keep it secret, keep it safe: web app security  Remember that <security-constraint> is about what happens after the request  Thus , we need to protect the data coming in from a request thats why we uses confidental to change the protocol http to https  79
  • 80. 9. The Power Filters  Sometimes you want to keep track of system’s response times across all of its different user interactions.  Filters are java components similar to servlets  Intercept and process requet before they are sent to the servlet  And before the response goes back to the client 80
  • 81. 9. The Power Filters  Filters doesn’t care which filters ran before it did or next  The DD controls the order in wich filters run  In the DD you can link the firlts by telling the container for these url run filtre x then filtre a … then run my servlet  Of course we can delete one or swap it  Why the filters like servlets : The container knows their API by implementing the Filter interface He manages their lifecycle (they have init() , destroy(), doPost()/Get +doFiltre() They’re declared in the DD 81
  • 82. 9. The Power Filters 82
  • 83. 9. The Power Filters  Every filtre must implements init and do filter and destroy  The doFilter( is called every time the container determines that the filter should be applied to the current request q Declaring and ordering filters  83
  • 84. 9. The Power Filters  <init-param> is optional and we can have many  <servlet-name> element defines which single web app resource will use this filter  Filters can be applied to request dispatchers too 84
  • 85. 9. The Power Filters  We cannot filtre the response because it’s too late the out put goes straight from the servlet back to the client  But we can swap our real response object with a custom response (wrapper classes) when we passing him to the servlet   Whenever you want to create a custom request or response object, just subclass one of the convenience request or response “wrapper” classes. A wrapper wraps the REAL request or response object, and delegates (passes through) calls to the real thing, while still letting you do the extra things you need for your custom request or response. 85
  • 86. 9. The Power Filters  ServletRequestWrapper  HttpServletRequestWrapper  ServletResponseWrapper  HttpServletResponseWrapper  public void doFilter( request, response, chain) { CompressionResponseWrapper wrappedResp = new CompressionResponseWrapper(response); chain.doFilter(request, wrappedResp); } 86