Sunteți pe pagina 1din 22

Click to edit Master text styles

Introduction to JSP

Agenda
Click to edit Master text styles
What is JSP?
Why JSP?
JSP Vs Servlets
Implicit objects in JSP
SP Scripting Elements
Life Cycle
Examples

What is a JSP Page?


Click to edit Master text styles
A text base document to serve static and dynamic contents to a client browser
Static and Dynamic Contents can be intermixed
Static Content
HTML, XML, Text
Dynamic Content
Invoking Java Code
Java Beans Properties
Business logic in Custom Tags

A Simple JSP Page Example


Click to edit Master text styles
(Black: Static content, Red: Dynamic content)
<html>
<body>
Hello World!
<br>
Current time is <%= new java.util.Date() %>
</body>
</html>
Output on the browser will show -

Hello World!
Current time is Sun Jun 17 14:39:53 IST 2007

Why JSP?
Click
If you
to are
editaMaster
text styles
programmer
or a web designer you will agree that not every programmer is a good
designer and not every good designer is a good programmer.
This is the exact problem posed by Java Servlets. Which means Java Servlets required the Java
programmer to know the designing skills because the Java Servlets did not separate the
Programming logic from the presentation layer.
Therefore there was a need to separate the design aspects from the Core Java programmers. This
was the reason why, JSP was introduced.

Why JSP?
JSP BenefitsClick
to edit Master text styles
Content and display logic are separated
Easier to develop web pages

Simplify web application development with JSP, JavaBeans (POJOs with getters, setters
and no argument constructor) and custom tags
Supports software reuse through the use of components (JavaBeans, Custom tags)
Automatic deployment
Recompile automatically when changes are made to JSP pages

Platform-independent

JSP Vs Servlets
Servlets can do a lot of things, but it is pain to:
Click
to edit
Master
text statements
styles
Use
those
println()
to generate HTML page

Maintain that HTML page


No need to explicitly compile, package or set CLASSPATH
We want to leverage the best of each technologies
Servlets strength is controlling and dispatching
JSPs strength is displaying
Best practice- In MVC (Model-View-Controller) pattern use
JavaBeans can be used as Models
JSP for view part
Servlets as controllers

Implicit objects in JSP


A JSP Page has access to certain implicit objects that are always available without being
Click
to edit Master text styles
declared
Created by Servlet and corresponds to classes defined therein
1.application javax.servlet.ServletContext -We can use it to get the RequestDispatcher object
2.session javax.servlet.http.HttpSession -user session management
3.request javax.servlet.http.HttpServletRequest - We can use request object to get the request parameters, cookies,
request attributes, session, header information and other details about client request
4.response javax.servlet.http.HttpServletResponse - We can response object to set content type, character encoding,
header information in response, adding cookies to response and redirecting the request to other resource
5.out javax.servlet.jsp.JspWriter (Output Stream for the page) -used to output content to be sent in client response
6.page java.lang.Object - age object provide reference to the generated servlet class.
7.pageContext java.servlet.jsp.PageContext - We can use pageContext to get and set attributes with different scopes
and to forward request to other resources
8.config javax.servlet.ServletConfig used to get the JSP init params configured in deployment descriptor
9.exception javax.servlet.jsp.JspException -used to provide exception details in JSP error pages

Implicit objects in JSP


Click to edit Master text styles

JSP Scripting Elements


Click to edit Master text styles

Three forms of JSP Scripting Elements


Expressions: <%= Expressions %>
Scriptlets: <% Code %>
Declarations: <%! Declarations %>

JSP Scripting Elements Expressions


During execution phase
Expressions
evaluated
and converted into String
Click to editare
Master
text styles
Streams are then inserted directly into Servlets output stream
out.println(Current time: + Sun Jun 17 14:39:53 IST 2007);

Format
<%= expression %>
<jsp:expression>expression</jsp:expression>
Semicolon are not allowed for expressions

Examples
Current time: <%= new java.util.Date() %>
Random number: <%= Math.random() %>

Invoking Java code using JSP scripting elements


JSP Scripting Elements Scriptlets
Click to
to edit
Master
text
styles
Used
insert
Java
code
into Servlets _jspService() method

Can do things which expressions alone can not do


setting response headers and status codes
writing to a server log
updating database
executing code that contains loops, conditionals

Format
<% Java Code %>
<jsp:scriptlet> Java code </jsp:scriptlet>

Examples
Display query string
<% String queryData = request.getQueryString(); %>

Invoking Java code using JSP scripting elements


Example: Scriptlet with loop
Click to edit Master text styles
<%
Iterator i = cart.getItems().iterator();
while (i.hasNext()) {

ShoppingCartItem item = (ShoppingCartItem)i.next();


BookDetails bd = (BookDetails)item.getItem();

%>
<tr>
<td align="right" bgcolor="#ffffff"> <%=item.getQuantity()%> </td>
<td bgcolor="#ffffaa"> <strong><a href= <%=request.getContextPath()%>/bookdetails?bookId=
<%=bd.getBookId()%>"><%=bd.getTitle()%>
</a> </strong> </td>
...
<%
} // End of while
%>

Resulting Servlet Code


public void _jspService (HttpServletRequest request, HttpServletResponse response) throws
ServletException,
Click
to edit MasterIOException
text styles
{
response.setContentType(text/html);
HttpSession session = request.getSession(true);
JSPWriter out = response.getWriter();
/* Static HTML fragment is sent to output stream in as is form out.println(<H2>Core HTML</H2>); */
/* Expression is converted into String and then sent to output
out.println(expressionString); */
/* Scriptlet is inserted as Java code within _jspService()
scriptlet_Code; */
...
}

JSP Scripting Elements


Declarations

Used to define variables or methods that get inserted into the main body of Servlet
class
Click to edit Master text styles
Outside _jspService()
Implicit objects are not accessible to declarations
Use declaration to override jspInit() and jspDestroy()
Format
<%! Java Code variables and methods %>
<jsp:declaration> variables and methods </jsp:declaration>
Examples
<H1>Some heading</H1>
<%!
private String randomHeading() {
return(<H2> + Math.random() + </H2>);
}%>

Resulting
Servlet class
public class xxxx implements HttpJSPPage {

Click to edit Master text styles

private String randomHeading() {

return(<H2> + Math.random() + </H2>);


}
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(text/html);
HttpSession session = request.getSession(true);
JSPWriter out = response.getWriter();
out.println(<H1>Some heading</H1>);
out.println(randomHeading());
...
}
...
}

Life Cycle of JSP Page


Click to edit Master text styles

How does JSP Work?

Life Cycle of JSP Page


Click to edit Master text styles
Life
Cycle Phases

Translation Phase
JSP page gets translated into a Servlet code

Compilation Phase
Servlet (java code) gets compiled

Execution Phase
Instance of the Servlet class is created
jspInit() method is executed
Servlet object is ready to serve the request; calls _jspService().
Once object is ready for destruction jspDestroy() is called

Translation and Compilation phase occur together usually

Translation/Compilation Phase
Click to edit Master text styles

JSP Engine parses the JSP file


If parsing is successful then engine translates it into Servlet source
code
Container automatically compiles the Servlet source code On its first
request after it is deployed or modified and redeployed
For a JSP Page the source code resides under work directory of the
application server as
<app_server_home>/work/Standard
Engine/localhost/context_root/filename_jsp.java
For example, in tomcat the index.jsp for the date application is saved at
<app_server_home>/work/catelina/localhost/date/index_jsp.java

Execution Phase
If the
instance
of the
Servlet class does not
Click
to edit
Master text
styles
exit
Container loads the Servlet class

Servlet class is instantiated


Container then initializes the Servlet class
by calling
jspInit() method
On a request, container calls the _jspService()
method, passing a request and response
objects.
If container needs to remove the Servlet
jspDestroy() is called

JSP directives introducton


Click to edit Master text styles
The jsp directives 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

<%@pageattribute="value"%>

include directive

<%@includefile="resourceName"%>

taglib directive
<
%@tagliburi="uriofthetaglibrary"prefix="prefixoftaglibrary"%>

Click to edit Master text styles

Thank You

S-ar putea să vă placă și