MELJUN CORTES JEDI Slides Web Programming Chapter04 Basic JSPs
Short Description
MELJUN CORTES JEDI Slides Web Programming Chapter04 Basic JSPs...
Description
Basic JSPs
Web Programming
Introduction ●
●
●
In the previous chapter, we have learned how to produce dynamic content for our users using Java technology through the use of servlets. However, while Java developers can create sites with such dynamic content using only servlets, there are several disadvantages in doing so: –
Using only servlets to produce HTML content does not make very maintainable or clean code.
–
Using only servlets to produce HTML content assumes that the developer is familiar with both Java & HTML.
This is where JSP technology comes in handy.
Web Programming
2
What is JSP? ● ●
●
Java Server Pages A servlet-based technology used in the web tier to present both dynamic and static content. Text-based and contains mostly HTML template text intermixed with tags specifying dynamic content.
Web Programming
3
Why JSP? ●
●
Since JSPs are text documents much like HTML, developers avoid having to format and manipulate a possibly very long String to produce output. The HTML content is now not embedded within a lot of Java code. This makes it easier to maintain. JSPs are immediately familiar to anyone with knowledge of HTML, with only the dynamic markup to learn. This makes it possible for dedicated site designers to create the HTML template of the site, with developers processing it later to include the tags producing dynamic content. This makes for ease of web page development.
Web Programming
4
Why JSP? ●
●
JSPs have built-in support for the use of reusable software components (JavaBeans). This not only lets developers avoid possibly reinventing the wheel for each application, having support for separate software components to handle logic promotes separation of presentation and business logic. JSPs, as part of Java's solution to web application development, are inherently multi-platform and can be run in any compatible servlet container, regardless of the vendor or operating system.
Web Programming
5
Why JSP? ●
Due to the way JSPs work, they do not need explicit compilation by the developer. This compilation is done for us by the servlet container. Modifications to JSPs are also automatically detected and result in recompilation. This makes them relatively simpler to develop.
Web Programming
6
Sample JSP Welcome Greetings! Thank you for accessing our site. The time is now
Web Programming
7
Output of Sample JSP
Web Programming
8
Running the Sample JSP ●
Using the IDE –
Assuming that a project already exists, simply place the JSP file within the Web Pages folder within the Project view.
Web Programming
9
Running the Sample JSP (Using the IDE continued) –
The specific JSP page can then be run from the IDE directly by pressing Shift + F6.
–
Alternatively, the web project can be packaged as a WAR file and uploaded into a server. The JSP can then be accessed by typing in the following URL: http://[host]:[port]/[WEB_PROJECT_NAME]/[JSP_NAME]
Web Programming
10
Running the Sample JSP ●
Using an Ant build file –
The JSP can also be run by packaging it into a WAR file using a build tool, and then deploying the WAR file into a web server. After build script has executed, will contain the application in a directory structure recognized by servlet containers.
After build script has executed, will contain the WAR file. Used to contain whatever documentation is used by the dev team. Directory under which all Java source files must be placed. Directory containing all static content of the app (HTML, JSP), will be the basis of the document root of your project. Directory containing configuration files such as the deployment descriptor (web.xml), tag library descriptors, etc.
●
Following the development directory structure discussed in the earlier chapter, our JSP file should be placed in the web directory.
Web Programming
11
JSP Lifecycle ●
●
The servlet container manages JSPs in a similar manner as it does to servlets: through the use of a well-defined lifecycle. JSPs have a three-phase lifecycle: –
Initialization
–
Service
–
Destruction
Web Programming
12
JSP and Equivalent Servlet ●
JSPs are compiled into an equivalent servlet class by the server. –
●
It is this servlet class that handles all requests to the JSP page.
If you wish to view the generated servlet class, installations of Sun Application Server 8.1 places them in the following directory: ${SERVER_HOME}/domains/domain1/generated/jsp/j2ee-modules/ ${WEB_APP_NAME}/org/apache/jsp
Web Programming
13
package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static java.util.Vector _jspx_dependants; public java.util.List getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; Web Programming
14
try {
_jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); response.addHeader("X-Powered-By", "JSP/2.0"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\n"); out.write("\n"); out.write(" Welcome\n"); out.write("\n"); out.write(" \n"); out.write(" Greetings! \n"); out.write("\n"); out.write(" Thank you for accessing our site. \n"); out.write("\n"); out.write(" The time is now "); out.print( new java.util.Date()); out.write("\n"); out.write("\n"); Web Programming
15
}
}
out.write(" \n"); out.write("\n"); out.write(""); }catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); }
Web Programming
16
JSP and Equivalent Servlet ● ●
●
It is not important to understand the code given. What is important here is to see that JSPs are handled just like Servlets, even if it is not immediately obvious. JSPs vs servlets: –
JSPs are more text-oriented.
–
Servlets allow the developer greater freedom with Java code.
Web Programming
17
JSP Syntax and Semantics ●
Elements and Template Data –
Components of all JavaServer Pages can be divided into two general categories: ●
Elements: dynamically produced information
●
Template data: static information that takes care of presentation
Hello World! Hello World! It's
Web Programming
18
JSP Syntax and Semantics (Elements and Template Data continued) –
Two Types of Syntax: ●
●
–
JSP Style: designed to be easier to the author XML Style: normal syntax modified to become XML-compliant and preferred when using JSP authoring tools
Choosing one syntax format over the other is just a matter of preference and standardization.
Web Programming
19
JSP Syntax and Semantics ●
Scripting Elements –
JSPs may be viewed as HTML or XML documents with embedded JSP scripts. JSP scripting elements allow you to insert Java code into the Servlet that will be generated from the JSP page.
–
The simplest way to make a JSP dynamic is by directly embedding scripting elements into template data.
–
JSP scripting elements: ●
Scriptlets
●
Expressions
●
Declarations
Web Programming
20
Scriptlets ●
Provide a way to directly insert bits of Java code in between chunks of template data: –
Just the same as writing normal Java code except that there is no need for a class declaration.
–
If you want to use the characters "%>" inside a scriptlet, write "%\>" instead.
●
Useful for embedding simple java codes
●
No specific limit as to the complexity of Java codes –
Overusing scriptlets: ●
●
Putting too heavy computation inside scriptlets is a code maintainability issue. Using scriptlets extensively violates JSPs role of being primarily a presentation layer component. Web Programming
21
Scriptlets ●
Simple println
Web Programming
22
Scriptlets ●
For-Loop in a scriplet
Web Programming
23
Scriptlets ●
Output of the For-Loop scriptlet
Web Programming
24
Scriptlets (Output continued) –
●
Take note that the scriptlet itself is not sent to the client but only its output. Try viewing the source of the jsp output you've produced in your browser to understand this point. All you should see are HTML tags plus the scriptlet output and minus the scriptlet.
The XML-compatible syntax for writing scriptlets is: Java code; .
Web Programming
25
Expressions ●
Provide a way to insert Java values directly into the output
●
–
It is actually short for out.println().
–
Notice that a semicolon ( ; ) does not appear at the end of the code inside the tag.
–
Evaluated at run-time, converted to a string, and inserted in the page.
Since it is evaluated at run-time, expressions have full access to information about the request.
Web Programming
26
Expressions ●
●
A number of predefined variables, called implicit objects, are made available to JSP authors to simplify expressions. The most important ones are: –
request: the HttpServletRequest;
–
response: the HttpServletResponse;
–
session: the HttpSession associated with the request (if any)
–
out: the PrintWriter (a buffered version of type JspWriter) used to send output to the client
Example: Hostname:
Web Programming
27
Expressions ●
XML-compatible syntax: Java Expression
Web Programming
28
Declarations ●
Allow you to define methods or variables.
●
Used to embed code just like scriptlets but declarations get inserted into the main body of the servlet class, outside of the _jspService() method processing the request. –
Advantage ●
–
Code embedded in a declaration can be used to declare new methods and global class variables.
Disadvantage ●
Code in declarations are not thread-safe.
Web Programming
29
Declarations ●
●
Reminders in using the declaration tag: –
Before the declaration you must have .
–
Code placed in this tag must end in a semicolon ( ; ).
–
Declarations do not generate output but are used with JSP expressions or scriptlets.
Since declarations do not generate any output, they are normally used in conjunction with JSP expressions or scriptlets.
Web Programming
30
Declarations ●
Example: AccessCountDeclaration.jsp
–
This JSP is able to print out the number of visits by declaring a class-wide variable accessCount, using a scriptlet to increment the value of the number of page visits and an expression to display the value. Web Programming
31
Declarations ●
Sample output of AccessCountDeclaration.jsp refreshed 4 times
Web Programming
32
AccessCountDeclaration_jsp.java package org.apache.jsp.JSP; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class AccessCountDeclaration_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private int accessCount = 0; private static java.util.Vector _jspx_dependants; public java.util.List getDependants() { return _jspx_dependants; } public void _jspService (HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException {
Web Programming
33
JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession();
Web Programming
34
out = pageContext.getOut(); _jspx_out = out; out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("Declaration Example\n"); out.write("\n"); out.write("\n"); accessCount++; out.write("Accesses to page since server reboot: \n"); out.print( accessCount ); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer();
Web Programming
35
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); } } }
Web Programming
36
Declarations ●
XML-compatible syntax: Java Code;
Web Programming
37
Template Text ●
Use
View more...
Comments