Download presentation
Presentation is loading. Please wait.
1
Introduction
2
JavaServer Pages In this lesson you will be learning about:
What JSP Technology is and how you can use it. How to define and write JSP Page. Syntax of JSP Page. How do JSP pages work. How is a JSP page invoked and compiled.
3
JavaServer Pages Technology
JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated content. The JSP 1.2specification is an important part of the Java 2 Platform, Enterprise Edition. Using JSP and Enterprise JavaBeans technologies together is a great way to implement distributed enterprise applications with web-based front ends. The first place to check for information on JSP technology is
4
JSP Page A JSP page is a page created by the web developer that includes JSP technology-specific tags, declarations, and possibly scriptlets, in combination with other static HTML or XML tags. A JSP page has the extension .jsp; this signals to the web server that the JSP engine will process elements on this page. Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.
5
Overview JavaServer Pages (JSP) lets you separate the dynamic part of your pages from the static HTML. HTML tags and text <% some JSP code here %> <I> <%= request.getParameter("title") %> </I> You normally give your file a .jsp extension, and typically install it in any place you could place a normal Web page
6
JSP page translation and processing phases
Translation phase Hello.jsp Read Request Client Server helloServlet.java Generate Response Execute Processing phase helloServlet.class
7
Template Pages translation Server Page Template <html>
<title> A simple example </title> <body color=“#FFFFFF”> The time now is <%= new java.util.Date() %> </body> </html> Resulting HTML <html> <title> A simple example </title> <body color=“#FFFFFF”> The time now is Tue Nov 5 16:15:11 PST 2002 </body> </html> translation
8
Dividing Pure Servlets
Public class MySelect { public void doGet(…){ if (isValid(..){ saveRecord(); out.println(“<html>”); …. } private void isValid(…){…} private void saveRecord(…) {…} controller view model Process request Servlet Presentation JSP JavaBeans Business logic Model-View-Controller (MVC) design
9
Translation Time A JSP application is usually a collection of JSP files, HTML files, graphics and other resources. A JSP page is compiled when your user loads it into a Web browser When the user loads the page for the first time, the files that make up the application are all translated together, without any dynamic data, into one Java source file (a .java file) The .java file is compiled to a .class file. In most implementations, the .java file is a Java servlet that complies with the Java Servlet API.
10
Simple JSP Page <%@ page info=“A Simple JSP Sample” %>
<HTML> <H1> First JSP Page </H1> <BODY> <% out.println(“Welcome to JSP world”); %> </BODY> </HTML>
11
User Request – JSP File Requested
How JSP Works? User Request – JSP File Requested Server File Changed Create Source from JSP Compile Execute Servlet
12
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
JSP Elements Declarations <%! code %> <jsp:declaration> </jsp:declaration > Expressions <%= expression %> <jsp:expression> </jsp:expression> Scriplets <% code %> <jsp:scriplet> </jsp:scriplet > Jordan Anastasiade. All rights reserved.
13
HTML Comment Generates a comment that is sent to the client. Syntax
<!-- comment [ <%= expression %> ] --> Example: <!-- This page was loaded on <%= (new java.util.Date()).toLocaleString() %> -->
14
Declaration Declares a variable or method valid in the scripting language used in the JSP page. Syntax <%! declaration; [ declaration; ] %> Examples <%! String destin; %> <%! Public String getDestination() {return destin;}%> <%! Circle a = new Circle(2.0); %> You can declare any number of variables or methods within one declaration element, as long as you end each declaration with a semicolon. The declaration must be valid in the Java programming language.
15
Declaration Example <HTML>
<HEAD><TITLE>JSP Declarations</TITLE></HEAD> <BODY><H1>JSP Declarations</H1> <%! private int keepCount = 0; %> <H2> Page accessed: <%= ++keepCount %> times </H2> </BODY> </HTML>
16
Predefined Variable – Implicit Objects
request – Object of HttpServletRequest (request parameters, HTTP headers, cookies response – Object of HttpServletResponse out - Object of PrintWriter buffered version JspWriter session - Object of HttpSession associated with the request application - Object of ServletContext shared by all servlets in the engine config - Object of ServletConfig pageContext - Object of PageContext in JSP for a single point of access page – variable synonym for this object
17
Expression Contains an expression valid in the scripting language used in the JSP page. Syntax <%= expression %> <%! String name = new String(“JSP World”); %> <%! public String getName() { return name; } %> <B><%= getName() %></B> Description: An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSPfile. Expressions are evaluated from left to right.
18
Expression Example <HTML> <HEAD>
<TITLE>JSP Expressions</TITLE> </HEAD> <BODY> <H2>JSP Expressions</H2> <UL> <LI>Current time: <%= new java.util.Date() %> <LI>Your hostname: <%= request.getRemoteHost() %> <LI>Your session ID: <%= session.getId() %> </UL> </BODY> </HTML>
19
Scriptlet Contains a code fragment valid in the page scripting language. Syntax <% code fragment %> <% String var1 = request.getParameter("name"); out.println(var1); %> This code will be placed in the generated servlet method: _jspService()
20
Scriplet Example <HTML>
<HEAD><TITLE>Weather</TITLE></HEAD> <BODY> <H2>Today's weather</H2> <% if (Math.random() < 0.5) { %> Today will be a <B>suny</B> day! <% } else { %> Today will be a <B>windy</B> day! <% } %> </BODY> </HTML>
21
Difference between Scriptlet and Declaration
Declaration :- Used for declaring variables and methods. example : <%! int num =0; %> During translation and compilation phase of JSP life cycle all variables declared in jsp declaration become instance variables of servlet class and all methods become instance methods. Since instance variables are automatically initialized all variables declared in jsp declaration section gets their default values. Scriptlet:- Used for embedding java code fragments in JSP page. example : <% num++; %> During translation phase of JSP Life cycle all scriptlet become part of _jspService() method. So we cannot declare methods in scriptlet since we cannot have methods inside other methods. As the variables declared inside scriptlet will get translated to local variables they must be initialized before use.
22
Example Using JSP Declarations
… <body> <h1>JSP Declarations</h1> <%! private int accessCount = 0; %> <h2>Accesses to page since server reboot: <%= ++accessCount %></h2> </body></html> A hit counter in two lines of code. Using fields to store persistent values is exceedingly useful. There are some caveats though: The count starts over when the server reboots. So, use jsplnit and jspDestroy to save/reload the count. Maybe periodically write val to disk in case of Northern California style rolling blackouts. Fields for persistence fails with distributed Web applications on a clustered server. In such a case, either mark the particular Web app non-distributable or use a database or other mechanism for persistence. EJBTM allows much more powerful persistence mechanisms. After 15 total visits by an arbitrary number of different clients INE2720 – Web Application Software Development All copyrights reserved by C.C. Cheung 2003.
23
JSP Lifecycle jspService() jspInit() jspDestroy() Servlet from JSP
Init Event jspService() Request Response jspDestroy() Destroy Event
24
JSP Page Directive page include Taglib
Directives are messages to the JSP container and do not produce output into the current output stream Syntax: directive attribute=“value” %> directive attribute1=“value1” attribute1 =“value2” … %> There are three types of directives: page include Taglib XML form: <jsp:directive.directiveType attribute=“value” />
25
Page Directive Defines attributes that apply to an entire JSP page.
[ language="java" ] [ extends="package.class" ] [ import="{package.class | package.*}, ..." ] [ session="true|false" ] [ buffer="none|8kb|sizekb" ] [ autoFlush="true|false" ] [ isThreadSafe="true|false" ] [ info="text" ] [ errorPage="relativeURL" ] [ contentType="mimeType [ ;charset=characterSet ]" [ isErrorPage="true|false" ] %>
26
Include Directive <%@ include file="relativeURL" %>
Includes a static file in a JSP file, parsing the file's JSP elements. Syntax include file="relativeURL" %> The include %> directive inserts a file of text or code in a JSP file at translation time, when the JSP file is compiled. include %> process is static. A static include means that the text of the included file is added to the JSP file. The included file can be: JSP file, HTML file, text file.
27
Taglib Directive Defines a tag library and prefix for the custom tags used in the JSP page. Syntax taglib uri="URIToTagLibrary" prefix="tagPrefix" %> taglib uri=" prefix="public" %> <public:loop> </public:loop> The taglib %> directive declares that the JSP file uses custom tags, names the tag library that defines them, and specifies their tag prefix.
28
HelloWorld.jsp
29
JSP Tags + HTML Tags <h2>Table of Square Roots</h2>
<table border=2> <tr> <td><b>Number</b></td> <td><b>Square Root</b></td> </tr> <% for (int n=0; n<=100; n++) { %> <td><%=n%></td> <td><%=Math.sqrt(n)%></td> } </table>
30
A First JSP calculator.html <html> <head></head>
<body> <p>Enter two numbers and click the ‘calculate’ button.</p> <form action=“calculator.jsp” method=“get”> <input type=text name=value1><br> <input type=text name=value2 ><br> <input type=submit name=calculate value=calculate> </form> </body> </html> calculator.html
31
Calculator.jsp <html>
<head><title>A simple calculator: results</title></head> <body> <%-- A simpler example 1+1=2 --%> 1+1 = <%= 1+1 %> <%-- A simple calculator --%> <h2>The sum of your two numbers is:</h2> <%= Integer.parseInt(request.getParameter("value1")) + Integer.parseInt(request.getParameter("value2")) %> </body> </html> Calculator.jsp
32
Server Redirection One can forward to a text file (HTML), a CGI script, a servlet or another JSP page. One can only forward to a new page, provided no output of the original page has been sent to the browser. One may pass as many parameters as one needs with this method by using the param tag. The forward action ends execution of the current JSP page and removes any existing buffered output. The new page has access to application, request, and session objects as the starting file. A new pageContext object is generated for the page. To the browser, it will appear you have the originally requested page, not the page to which you are transferred. Example: <jsp:forward page="home/Default.jsp" > <jsp:param name="source" value="entry"/> </jsp:forward>
33
<jsp:forward> Forwards a client request to an HTML file, JSP file, or servlet for processing. Syntax <jsp:forward page="{relativeURL | <%= expression %>}" /> <jsp:forward page="{relativeURL | <%= expression %>}" > <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+ </jsp:forward>
34
As you see in the below figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user
35
Example : jsp forward index.jsp display.jsp
36
As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client.
37
Example of RequestDispatcher interface
38
Example.jsp Process.jsp index1.jsp
39
Conclusion JavaServer Pages (JSP) lets you separate the dynamic part of your pages from the static HTML. 1. One can simply write the regular HTML in the normal manner, using whatever Web-page-building tools you normally use. One can enclose then the code for the dynamic parts in special tags, most of which start with "<%" and end with "%>"
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.