JSP vs Servlets
•Similarities
–Provides identical results to
end user.
–JSP is an extension of
servlets.
–Provides similar API support.
3.
• Differences
– Servlets:“HTML embedded in Java Code”
HTML code inaccessible to Graphics designer
But accessible to Programmer.
– JSP: “Java Code embedded in HTML”
HTML code accessible to Graphic Designer
Java code accessible to Programmer.
– Jsp allows code update without restarting
the server.
– Eliminates redundant code.
4.
The Anatomy ofa JSP Page
• A JSP page is simply a regular web page with
JSP elements for generating the parts that
differ for each request
6.
• Everything inthe page that isn't a JSP element is
called template text.
• template text can be any text: HTML, WML, XML,
or even plain text
• Template text is always passed straight through to the
browser
• When a JSP page request is processed,
– the template text and dynamic content generated by the JSP
elements are merged, and the result is sent as the response
to the browser
7.
JSP Processing
• theweb server needs a JSP container to process JSP pages.
• The JSP container is responsible for intercepting requests for JSP pages.
• To process all JSP elements in the page, the container first turns the JSP
page into a servlet known as the JSP page implementation class
• all template text is converted to println( ) statements and all JSP elements
are converted to Java code that implements the corresponding dynamic
behavior.
• The container then compiles the servlet class.
8.
• all templatetext is converted to println( ) statements and all
JSP elements are converted to Java code that implements the
corresponding dynamic behavior
• Converting the JSP page to a servlet and compiling the servlet
form the translation phase.
• The JSP container initiates the translation phase for a page
automatically when it receives the first request for the page.
• Since the translation phase takes a bit of time, the first user to
request a JSP page notices a slight delay.
• The translation phase can also be initiated explicitly; this is
referred to as precompilation of a JSP page
10.
• request processingphase
• The JSP container is also responsible for invoking the
JSP page implementation class (the generated servlet)
to process each request and generate the response.
• As long as the JSP page remains unchanged, any
subsequent request goes straight to the request
processing phase
• When the JSP page is modified, it goes through the
translation phase again before entering the request
processing phase.
11.
• a servletcontainer and a JSP container--are often
combined in one package under the name web
container
• a JSP page inherits all the advantages of a servlet:
– platform and vendor independence
– integration
– efficiency
– scalability
– robustness
– and security
12.
• _jspInit()
• _jspDestroy()
•_jspService( request, response )
JSP life cycle
_jspInit()
Initialise JSP
Invoked only once
_jspService(request,r
esponse)
Handle Requests:
invoked
for every request
_jspDestroy()
Invoked by
container
to cleanup
13.
• Contract betweenthe JSP engine and JSP
– _jspInit() Corresponds to servlet init(), but has no parameters (use
config implicit object to obtain information regarding environment)
– _jspService() The main processing method; all Java code belongs to
this method by default (if not contained in another method), but it is
not explicitly declared in a JSP document
– _jspDestroy() Corresponds to the servlet destroy() method and is
called just before the generated servlet is destroyed
14.
JSP Elements
• Threedifferent elements are used in
constructing JSPs
– Scripting Elements
– Directives
– Actions
15.
Scripting Elements
• Thereare three kinds of scripting elements
– Declarations
– Scriptlets
– Expressions
16.
Declarations
• Declarations areused to define methods & instance variables
• Do not produce any output that is sent to client
• Embedded in <%! and %> delimiters
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
• The functions and variables defined are available to the JSP Page as well as to the
servlet in which it is compiled
17.
Scriptlets
• Used toembed java code in JSP pages.
– Contents of JSP go into _JSPpageservice() method
– Code should compile with syntactical and semantic constuct of java
– Embedded in <% and %> delimiters
Example:
<%
int x = 5;
int y = 7;
int z = x + y;
%>
Expressions
• Used towrite dynamic content back to the browser.
• If the output of expression is Java primitive the value is printed back to the
browser
• Embedded in <%= and %> delimiters
• Example:
– <%= new java.util.Date() %>
– I
Index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
Welcme.jsp
<html>
<body>
<%= "Welcome
"+request.getParameter("uname") %>
</body>
</html>
20.
JSP Implicit Objects
•request: HttpServletRequest
– Reference to the current request
• response: HttpServletResponse
– Response to the request
• session: HttpSession
– session associated with current request
• application: ServletContext
– Servlet context to which a page belongs
• pageContext: PageContext
– Object to access request, response, session and application associated with a page
• config: ServletConfig
– Servlet configuration for the page
• out: JspWriter
– Object that writes to the response output stream
• page: Object
– instance of the page implementation class (this)
• exception: Throwable
– Available with JSP pages which are error pages
• In JSP,pageContext is an implicit object of type
PageContext class.
• The pageContext object can be used to set,get or
remove attribute from one of the following
scopes:
– page
– request
– session
– application
Directives
• The jspdirectives are messages that tells the web container
how to translate a JSP page into the corresponding servlet.
• There are three types of directives:
– page directive
– include directive
– taglib directive
– Syntax:
<%@ directive attribute="value" %>
28.
JSP page directive
•The page directive defines attributes that apply to an entire JSP page
• Syntax:
– <%@ page attribute="value" %>
• Attributes of JSP page directive
– import
• Declares the packages and classes that need to be imported for using in the java
code
– <%@ page import="java.util.Date" %>
– Today is: <%= new Date() %>
– contentType
• Defines MIME type for the output response
• <%@ page contentType=application/msword %>
– extends
• Declares the class which the servlet compiled from JSP needs to extend
– info
• String returned by the getServletInfo() of the compiled servlet
<%@ page info=“Created by rajashekar" %>
– buffer
• defines buffer size of the jsp in kilobytes
• <%@ page buffer="16kb" %>
29.
• language
• Definesserver side scripting language
• isThreadSafe
• If false the compiled servlet implements SingleThreadModel interface
• <%@ page isThreadSafe="false" %>
• autoFlush
• When true the buffer is flushed when max buffer size is reached
• <% @ page autoFlush="true/false" %>
• session
• JSP page creates session by default.
• Boolean which says if the session implicit variable is allowed or not
• <%@ page session="true/false"%>
30.
• errorPage
• Definesthe relative URI of web resource to which the response should be
forwarded in case of an exception
• <%@ page errorPage="myerrorpage.jsp" %>
• isErrorPage
• True for JSP pages that are defined as error pages
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
• In JSP,exception is an implicit object of type java.lang.Throwable class.
• This object can be used to print the exception.
• But it can only be used in error pages.
myerrorpage.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>
33.
Jsp Include Directive
•The include directive is used to include the contents of any resource it may
be jsp file, html file or text file
• The include directive includes the original content of the included resource
at page translation time
• Advantage: Code Reusability
• Syntax: <%@ include file="resourceName" %
JSP Taglib directive
•The JSP taglib directive is used to define a tag library that defines many
tags.
• used to import custom actions defined in tag libraries
• We use the TLD (Tag Library Descriptor) file to define the tags.
• Syntax:
– <
%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
36.
JSP Action Tags
•There are many JSP action tags or elements.
• Each JSP action tag is used to perform some specific tasks.
• The action tags are used to control the flow between pages and to use Java
Bean.
37.
• jsp:forward forwardsthe request and response to
another resource.
• jsp:include includes another resource.
• jsp:useBean creates or locates bean object.
• jsp:setProperty sets the value of property in bean object.
• jsp:getProperty prints the value of property of the bean.
• jsp:plugin embeds another components such as applet.
• jsp:param sets the parameter value. It is used in forward
and include mostly.
38.
jsp:forward
• The jsp:forwardaction tag is used to forward the
request to another resource it may be jsp, html or
another resource.
• <jsp:forward page="relativeURL | <
%= expression %>" />
• <h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value=“VJIT" />
</jsp:forward>
<
% out.print("Today is:"+java.util.Calendar.getIn
stance().getTime()); %>
<%= request.getParameter("name") %>
39.
jsp:include
• The jsp:includeaction tag is used to include the content of
another resource it may be jsp, html or servlet.
• The jsp:include action tag includes the resource at request
time so it is better for dynamic pages
• The jsp:include tag can be used to include static as well as
dynamic pages.
<jsp:include page="relativeURL | <%= expression %>" />
40.
JSP include directiveJSP include action
includes resource at translation
time.
includes resource at request
time.
better for static pages. better for dynamic pages.
includes the original content in
the generated servlet.
calls the include method.
41.
jsp:useBean action tag
•The jsp:useBean action tag is used to locate or instantiate a
bean class
• If bean object of the Bean class is already created, it doesn't
create the bean depending on the scope.
<jsp:useBean id= "instanceName" scope= "page | request | session | ap
plication"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
42.
• id: isused to identify the bean in the specified scope
• scope: represents the scope of the bean
– page: specifies that you can use this bean within the JSP page.
• The default scope is page.
– request: specifies that you can use this bean from any JSP page that processes the same
request.
• It has wider scope than page.
– session: specifies that you can use this bean from any JSP page in the same session whether
processes the same request or not.
• It has wider scope than request.
– application: specifies that you can use this bean from any JSP page in the same application.
• It has wider scope than session.
• class: instantiates the specified bean class
• type: provides the bean a data type if the bean already exists in the scope. It is
mainly used with class or beanName attribute
• beanName: instantiates the bean using the java.beans.Beans.instantiate() method.
43.
• The setPropertyand getProperty action tags
are used for developing web application with
Java Bean
• In web development, bean class is mostly used
because it is a reusable software component
that represents data
44.
jsp:setProperty
• The jsp:setPropertyaction tag sets a property
value or values in a bean using the setter method.
<jsp:setProperty name="instanceOfBean" property= "*" |
property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <
%= expression %>}"
/>
jsp:getProperty
• The jsp:getPropertyaction tag returns the value of the property
• Syntax:
– <jsp:getProperty name="instanceOfBean" property="prope
rtyName" />
• Example:
– <jsp:getProperty name="obj" property="name" />
MVC in JSP
•MVC stands for Model View and Controller.
• It is a design pattern that separates the business logic,
presentation logic and data.
• Model represents the state of the application i.e. data. It can
also have business logic.
• View represents the presentation i.e. UI(User Interface).
• Controller acts as an interface between View and Model.
– Controller intercepts all the incoming requests.
52.
MODEL
● This isthe data layer which consists of the business logic of the
system.
● It consists of all the data of the application
● It also represents the state of the application.
● The controller connects with model and fetches the data and
sends to the view layer.
● The model connects with the database as well and stores the
data into a database which is connected to it.
53.
View Layer:
● Thisis a presentation layer.
● It consists of HTML, JSP, etc. into it.
● It normally presents the UI of the application.
● It is used to display the data which is fetched from the controller which in
turn fetching data from model layer classes.
54.
Controller Layer:
● Itacts as an interface between View and Model.
● It intercepts all the requests which are coming from the view layer.
● It receives the requests from the view layer and processes the
requests and does the necessary validation for the request.
● This requests is further sent to model layer for data processing, and
once the request is processed, it sends back to the controller with
required information and displayed accordingly by the view.
Session Tracking inJSP
• In JSP, by default a session is automatically created for the request
if one does not exist.
• So if your starting page is a JSP, a session would have already been
created when you get the first request.
• 1. Setting Session :
• use session.setAttribute("ATTRIBUTE NAME","ATTRIBUTE VALUE")
method for setting value in session.
• 2. Retrieving values from session attribute :
• To retrieve value from session attribute we need to use following
method. session.getAttribute("attribute name");
<%
String name =request.getParameter("name");
String password = request.getParameter("password");
if (name.equals(“Rajasheakr") && password.equals(“Parupati")) {
session.setAttribute("username", name);
response.sendRedirect("secondpage.jsp");
}
else {
response.sendRedirect("index.jsp");
}
%>
<html>
<head>
<title>Welcome in the program of
session</title>
</head>
<body>
<font size = 5>Hello <%=
session.getAttribute("username") %></font>
</body>
</html>
59.
Session Tracking usingCookies
• Creating a Cookie object
– Cookie c = new Cookie("key","value");
• Setting the maximum age
– c.setMaxAge(60*60*24);
• Sending the Cookie into the HTTP response
headers
– response.addCookie(cookie);
• Reading Cookies with JSP
60.
• Reading Cookieswith JSP
– To read cookies, you need to create an array of Cookie
objects by calling the getCookies( ) method
of HttpServletRequest
– use getName() and getValue() methods to access each
cookie and associated value
61.
<html>
<body>
<form action ="main.jsp" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
62.
<%
// Create cookiesfor first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
%>
63.
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookiecookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null ) {
out.println("<h2> Found Cookies Name and
Value</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html>