The document provides an overview of JavaServer Pages (JSP) technology including the role of JSP pages, the JSP execution model, lifecycle, core syntax elements like directives, declarations, scriptlets and expressions, and how JSP interacts with HTML, servlets and other JSP pages.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
59 views44 pages
3-JSP Basic
The document provides an overview of JavaServer Pages (JSP) technology including the role of JSP pages, the JSP execution model, lifecycle, core syntax elements like directives, declarations, scriptlets and expressions, and how JSP interacts with HTML, servlets and other JSP pages.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44
JSP Basic
10/1/2014 JSP Basic 1
Topic • JavaServer Pages technology • The role of JSP pages within Web applications • JSP execution model • JSP lifecycle • Core JSP syntax – Directives – Declarations – Scriptlets – Expressions • JSP interaction with HTML, servlets and other JSP pages 10/1/2014 JSP Basic 2 Content within a Web Page
• Content delivered to a client is composed from:
– Static or non-customized content – Customized content • Page layout and style are managed through HTML, XSL 10/1/2014 JSP Basic 3 What is JSP Page? • JavaServer Pages is a technology that lets you mix static HTML with dynamically generated HTML • JSP technology allows server-side scripting: – Static tags are HTML or XML or other markup language. – Dynamic content generated by scripting code • Java is the (default) scripting language • A JSP file (has an extension of .jsp) contains any combination of: – JSP syntax – Markup tags such as HTML or XML
10/1/2014 JSP Basic 4
A Simple JSP Page <HTML> <HEAD><TITLE>Our WebSite Home</TITLE></HEAD> <BODY background="image.jpg" text="#ffffff"> <TABLE> <TR><TD> <H1>Welcome to Our WebSite</H1> </TD></TR> <TR><TD> <H3>Today's date is
JSP or Servlet? • Use servlets to: – Determine what processing is needed to satisfy the request – Validate input – Work with business objects to access the data and perform the processing needed to satisfy the request – Control the flow through a Web application • Use JSP pages for displaying the content generated by your Web application • In a typically production environment, both servlet and JSP are used in a Model-View-Controler (MVC) pattern – Servlet handles controller part – JSP handles view part 10/1/2014 JSP Basic 7 JSP Benefits (1 of 2) • Separation of static from dynamic content – The logic to generate the dynamic content is kept separate from the static presentation by encapsulating it within external (JavaBeans) components – Separation of workload • Easier to author web pages • Write Once Run Anywhere – Easily moved between platforms, no rewriting necessary • J2EE-Compliant – The J2EE Blueprint recommends using JSP pages over servlets for the presentation of dynamic data 10/1/2014 JSP Basic 8 JSP Benefits (2 of 2) • Leverages the Servlet API – The JSP specification is a standard extension defined on top of the Servlet API • Reuse of components and tag libraries – JSP technology emphasizes the use of reusable components such as JavaBeans, Enterprise JavaBeans, and tag libraries • High-quality tool support – One goal of the JavaServer Pages design is to enable the creation of JSP development tools, such as Page Designer in Application Developer
10/1/2014 JSP Basic 9
Separate Request processing, Business logic, and Presentation
10/1/2014 JSP Basic 10
JSP Execution Model (1 of 2) • A JSP page is executed in a Web Container – The Web Container delivers client requests to the JSP page and returns the page’s response to the client • The JSP page is converted into a servlet (JSP servlet) and executed • This process is known as PageCompilation: – JSP source is parsed – Java servlet code is generated – This JSP servlet is compiled, loaded, and run
10/1/2014 JSP Basic 11
JSP Execution Model (2 of 2) • Compilation is only performed as needed: – No class file exists, or – JSP has been updated since last compilation • Precompilation – The JSP 2.0 specification requires support by the container for precompilation – All request parameters starting with jsp_ are reserved • JSP pages should ignore parameters starting with jsp_
10/1/2014 JSP Basic 12
Life-Cycle of a JSP Page
10/1/2014 JSP Basic 13
JSP Lifecycle Methods during Execution Phase
10/1/2014 JSP Basic 14
Initialization and Finalization a JSP Initialization • Declare methods for performing the following tasks – Read persistent configuration data – Initialize resources – Perform any other one-time activities by overriding jspInit() method of JspPage interface Finalization • Declare methods for performing the following tasks – Read persistent configuration data – Release resources – Perform any other one-time cleanup activities by overriding jspDestroy() method of JspPage interface
10/1/2014 JSP Basic 15
JavaServer Pages Fundamental
10/1/2014 JSP Basic 16
JSP Syntax Elements JSP elements fall into groups: • Scripting – Comments – Declarations – Expressions – Scriptlets • Directives • Actions – Directives and scripting have both non-XML syntax and XML syntax – Actions are only written in XML syntax • JSP Expression Language (from JSP 2.0)
10/1/2014 JSP Basic 17
JSP Scripting Elements • Lets you insert Java code into the servlet that will be generated from JSP page • Minimize the usage of JSP scripting elements in your JSP pages if possible • There are three forms – Comments: <%-- comment --%> – Declarations: <%! Declarations %> – Scriptlets: <% Code %> – Expressions: <%= Expressions %>
10/1/2014 JSP Basic 18
Comment • A good way of explaining any complicated logic that may have arisen for whatever reason <%-- This is a JSP comment --%> • Get stripped out during the translation phase and aren't sent to the client as part of the response. • HTML comments sent to a client's browser and any client can view the comments by using the View Source options <!--This is an HTML comment -->
10/1/2014 JSP Basic 19
Declarations • Used to define variables or methods that get inserted into the main body of servlet class – Outside of _jspSevice() method – Implicit objects are not accessible to declarations • Format: <%! declaration %> • Example
<%! Date now = new Date(); %>
<%! private int calculate(int a, int b) { ... } %>
10/1/2014 JSP Basic 20
Example: Declaration initdestroy.jsp • For initialization and cleanup in JSP pages, use declarations to override jspInit() and jspDestroy() methods <%! private BookDBAO bookDBAO; public void jspInit() { // retrieve database access object, which was set once // per web application bookDBAO =(BookDBAO)getServletContext().getAttribute("bookDB"); if (bookDBAO == null) System.out.println("Couldn't get database."); } public void jspDestroy() { bookDBAO = null; } %> 10/1/2014 JSP Basic 21 Scriptlets • Used to insert arbitrary Java code into servlet's jspService() method • Can do: – setting response headers and status codes, – writing to a server log, – updating database, – executing code that contains loops, conditionals • Can use predefined variables (implicit objects) • Format: <% Java code %>
10/1/2014 JSP Basic 22
Example: Scriptlets • Display query string <% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %> • Setting response type <% response.setContentType("text/plain"); %> • Executing code that contains conditionals <% if (Calendar.getInstance() .get(Calendar.AM_PM)==Calendar.AM) { %> How are you this morning? <% } else { %> How are you this afternoon? <% } %> 10/1/2014 JSP Basic 23 Expressions • During execution phase – Expression is evaluated and result is converted into a String – The String is then inserted into the servlet's output stream directly – Results in something like out.println(expression) – Can use predefined variables (implicit objects) within expression • Format <%= expression %> • Semi-colons are not allowed for expressions 10/1/2014 JSP Basic 24 Example: Expressions • Display current time using Date class – Current time: <%=new java.util.Date()%> • Display random number using Math class – Random number: <%=Math.random()%> • Use implicit objects – Your parameter: <%=request.getParameter("param")%> – Server: <%=application.getServerInfo()%> – Session ID: <%=session.getId()%>
10/1/2014 JSP Basic 25
Implicit objects • Within both Scriptlets and Expressions there are certain implicit objects available for use. – Created by container • Implicitly defined variables available for scripting: – request - HttpServletRequest object – response - HttpServletResponse object – pageContext - The PageContext for this JSP – session - HttpSession object (if any) – application - the ServletContext object – config - ServletConfig object for this JSP – out - JspWriter – page - Page’s implementation class processing the current – exception - the Throwable object passed to this error page
10/1/2014 JSP Basic 26
Scope Factors Scope Type Implicit Factor Variable page PageContext pageContext Used internally by page compiler and by custom tag libraries request ServletRequest request Information relevant to a specific user for a specific HTTP request/response pair. session HttpSession session Information relevant to a specific user for a series of request/response pairs. application ServletContext application Information specific to a group of users across multiple servlets in a Web application
10/1/2014 JSP Basic 27
Using Scope Objects • Scope object enables sharing information among collaborating web application
components via attributes maintained session
in Scope objects request • A JSP page can access objects at run page time via one of four different scopes – page: The current JSP page, used with Custom Actions – request: current HttpServletRequest object – session: current HttpSession object – application: current ServletContext object 10/1/2014 JSP Basic 28 Page Scope • Objects are available only within the page where they are created application • References to these objects are session released after the response is sent request back to the client or when the request page is forwarded to somewhere else • Use setAttribute(String, Object) to set and getAttribute(String) to retrieve • References to objects with page scope are stored in the pageContext object
10/1/2014 JSP Basic 29
Request Scope • Objects are available within the page where they are created, and pages to application which the current request is forwarded session • References to these objects are released request after the response is sent back to the client page • References to objects with request scope are stored in the request object • To store objects in the request context: – Use HttpRequest.setAttribute(String, object) in the servlet – JSP pages use request.getAttribute(String) to retrieve values
10/1/2014 JSP Basic 30
Session Scope • Objects are available from servlets and JSP pages processing requests that application are in the same user session session • References to the object are be released after the associated session request ends page • References to objects with session scope are stored in the session object • To store objects in the session context: – Use HttpSession.setAttribute(String, Object) in the servlet – JSP pages use session.getAttribute(String) to retrieve values
10/1/2014 JSP Basic 31
Application Scope • Objects are available from servlets and pages processing requests that are in the application same application session • References to the object are released when the run-time environment reclaims the request ServletContext object page • References to objects with application scope are stored in the application object • To store objects in the application context: – Use ServletContext.setAttribute(String, Object) in the servlet – JSP pages use application.getAttribute(String) to retrieve values
10/1/2014 JSP Basic 32
Including and Forwarding to Other Web Resource
10/1/2014 JSP Basic 33
Including Contents in a JSP Page
• Two mechanisms for including another
Web resource in a JSP page – include directive – jsp:include element
10/1/2014 JSP Basic 34
Include Directive • Syntax and Example <%@ include file="relativeURLspec" %> – Example: <%@ include file="banner.jsp" %> • Is processed when the JSP page is translated into a servlet class • Effect of the directive is to insert the text contained in another file – either static content or another JSP page – in the including JSP page • Used to include banner content, copyright information, or any chunk of content that you might want to reuse in another page
10/1/2014 JSP Basic 35
jsp:include Action Element • Syntax and Example <jsp:include page="includedPage" /> – Example: <jsp:include page="date.jsp"/> • Is processed when a JSP page is executed • Allows you to include either a static or dynamic resource in a JSP file – static: its content is inserted into the calling JSP file – dynamic: • the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page • Execution of current page continues after including response from target 10/1/2014 JSP Basic 36 Which One to Use it? • Use <%@include ...> directive if the file changes rarely – It is faster than jsp:include
• Use jsp:include for content that changes often
• Use jsp:include if which page to include cannot be decided until the main page is requested <jsp:include page="<%= contentpage %>"/>
10/1/2014 JSP Basic 37
Forwarding to another Web component • Same mechanism as in Servlet • Syntax and Example <jsp:forward page="forwardpage" /> – Example: <jsp:forward page="/main.jsp" /> • Execution of current page is terminated and target resource has full control over request • Original request object is provided to the target page via jsp:param element <jsp:forward page="..." > <jsp:param name="param1" value="value1"/> </jsp:forward> 10/1/2014 JSP Basic 38 JSP Interactions • A JSP page can be invoked: – By URI – By a servlet – By another JSP page • JSP page can invoke: – A servlet – Another JSP page
10/1/2014 JSP Basic 39
Invoking a JSP by URL • A JSP page can be invoked by URL, – from within the <FORM> tag of a JSP or HTML page, – or from another JSP page
Calling a JSP Page from a Servlet • JSP pages can be called using the same RequestDispatcher interface used to call servlets from servlets – getServletContext().getRequestDispatcher ("/pages/showResults.jsp") .forward(request, response);
OR – request.getRequestDispatcher ("/pages/showResults.jsp") .forward(request, response);
10/1/2014 JSP Basic 41
Invoking a Servlet from a JSP Page • You can invoke a servlet from a JSP page – either as an action on a form, – or directly through the jsp:include or jsp:forward tags. • To invoke a servlet within the HTML <FORM> tag, the syntax is: <FORM METHOD="POST | GET" ACTION="application_URI /Servlet_URL"> <!--Other tags such as text boxes and buttons go here --> </FORM>
10/1/2014 JSP Basic 42
Invoking a JSP Page from another JSP Page To invoke a JSP file from another JSP file, you can: • Specify the URL of the second JSP file on the FORM ACTION attribute: <FORM ACTION="/MYAPP/DateDisplay.jsp"> • Specify the URL of the second JSP file in an anchor tag HREF attribute: <a HREF="/MYAPP/InfoDisplay.jsp">reference- text</a>
10/1/2014 JSP Basic 43
JSP Issues • Advantages: – Can build and maintain presentation using page authoring tools – Full support for Java on server-side • Disadvantages: – Excessive Java code pollutes HTML – Poor separation of responsibility (.jsp owned by both Page Designer and Logic Developer)