JSP - Java Server Pages JSP Java Server Pages
JSP - Java Server Pages Characteristics: A way to create dynamic web pages, Server side processing, Based on Java Technology, Large library base Platform independence Separates the graphical design from the dynamic content. Ref.: http://java.sun.com/products/jsp
JSP - Java Server Pages Basic idea: Separating Graphical Design and Dynamic Content Similar approaches: PHP, SSI, ASP Graphical Design and System Design are two separate and distinct specialities: Different languages (HTML/XHTML vs. Java), Different goals, and Different Training. Should be separated for optimal project management. JSP way: special Java tags in HTML.
JSP - Code Example <html> <body> <b>hello World HTML!</b><br><br> <% out.println("hello World Java"); %> </body> </html> http://149.222.51.81:8180/home-tomcat/jsp/dispert/hello.jsp
JSP - Code Example with Errors <html> <body> <b>hello World HTML!</b><br><br> <% out.println("hello World Java") %> </body> </html> http://http://149.222.51.81:8180/home-tomcat/jsp/dispert/helloerror.jsp Missing ";"
JSP - Code Example with Errors
Java Server Pages JSP technology is essentially a language specification Used to mix code into text content Typically HTML or XML Special syntax embedded into pages compile Directive blocks code block Code snippets that generate into strings Compile into a servlet
Java Server Pages Servlet Java Code out.println("html") JSP HTML Page <% Java %> HTML Java HTML Java
Java Server Pages JSP JSP Compiler Servlet Source Java Compiler Class File
Servlets / Java Server Pages Browser XML + HTML JSP/Servlet JDBC Browser X,D-HTML EJB EJB XSL/XTL XML App App
JSP Engine Client (HTML File) Response Request (HTTP get or post) JSP Engine and Web Server (Creates a Servlet from a JSP file and executes the servlet) Request Response Servlet File Request Response Java Component
JSP Engine User request a JSP Page compiled before? No Yes Page unchanged? No Compile JSP into Servlet Yes Execute Servlet
JSP Processing JSP Elements must first be processed by the server JSP Page => Servlet Compile Servlet Execute Servlet Web server must have JSP Container
JSP Translation/Processing Hello.jsp (2) READ (1) GET / Hello.jsp CLIENT (6) HTTP/1.0 200 OK <html>... </html> Server (JSP) (3) GENERATE HelloServlet.java (5) EXECUTE (4) COMPILE HelloServlet.class
JSP versus Javascript Javascript Client side Less secure Browser dependent Unstable
JSP versus ASP Active Server Pages (ASP, Microsoft) Many similarities Server side dynamic web page generator Separate programming logic from page design Similar syntax <% %> Proprietary Product Limited platform
JSP versus Servlets Disadvantages of Servlets Processing code & HTML code in same module Changing look and feel requires servlet recompilation Difficult to leverage web development tools Generated HTML embedded into Servlet
JSP versus Servlets Similarities between JSP and Servlets Identical results to the end user JSP is an additional module to the Servlet Engine Differences Servlets HTML in Java code : HTML code inaccessible to Graphics Designer, Everything is accessible to Programmer JSP Java Code Scriptlets in HTML : HTML code very accessible to Graphics Designer, Java code very accessible to Programmer
JSP Architecture JSP is a simple text file consisting of HTML or XML content along with JSP elements JSP packages define the interface for the compiled JSP page JSPPage HttpJspPage Three main methods jspinit() jspdestroy() jspservice(httpservletrequest request, HttpServletResponse response)
Elements of a JavaServer Page JSP Elements Template Text -HTML When request is processed template text & dynamic content merged result sent as response to browser JSP Elements Directive Action Scripting
Elements of a JavaServer Page Directives provide global information to the page Action perform action based on up-to-date information Scripting Declarative: for page-wide variable and method declaration Scriptlets: the Java code embedded in the page Expressions: Format the expression as a string for inclusion in the output of the page.
JSP Syntax HTML Comment Comment can be viewed in the HTML source file <!-- comment <% expression%> --> Example: <!--this is just Html comment --> <!-- This page was loaded on <%= (new java.util.date ()).tolocalestring()%> --> View source: <!--this is just Html comment --> <!--This page was loaded on January 10, 2006 -->
JSP Syntax Hidden Comment Comment cannot be viewed in the HTML source file <% --expression --%> Example: <html> <body> <h2>a Test of Comments</h2> <%--This comment will be invisible in page source --%> </body> </html>
JSP Directives A JSP directive is a statement that gives the JSP engine information for the page. Syntax: - <%@ directive {attribute= value } %> For example - scripting language used - session tracking required - name of page for error reporting
Types of Directive Elements <%@ page... %> Define page-dependent attributes, such as scripting language, error page & buffering requirements. <%@ include... %> Include a file during the translation phase. <%@ taglib... %> Declares a tag library, containing custom actions (markup tags), used in the page.
JSP Syntax: Include Directive Includes a static file <%@ include file="relativeurl" %> Example: JSP-File "main.jsp": <html><body> Current date and time is: <%@include file="date.jsp" %> </body></html> Include code here File to include "date.jsp": <%@page import ="java.util.*" %> <% =(new java.util.date()).tolocalestring() %> Output : Current date and time is: Mar 5, 2010 4:56:50
Page Directive - Attributes/Values Attribute language extends import session buffer autoflush isthreadsafe info errorpage iserrorpage Values java package.class package.* / package.class true / false none / 8kb / sizekb true / false true / false text pathtoerrorpage true / false
JSP Declaration The definition of class-level variables and methods Syntax: <%! Declaration %> <%! String var1 = "hi"; int count = 0; private void incrementcount() { count++; } %>
JSP Scriptlets Scriptlets definition: any block of valid Java code that resides between <% and %> tags. This code will be placed into the generated servlet_jspservice() method. <% String var1 = request.getparameter("lname"); out.println(var1); %>
JSP Expressions JSP expression: used to embed values directly within HTML code. Syntax: <%= expression %> Example: <% for (int i=0; i<10; i++) { %> <BR> Counter value is <%= i %> <% } %> http://149.222.51.81:8180/home-tomcat/jsp/dispert/counter.jsp
JSP Expressions <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() %> <LI>The <CODE>testParam</CODE> form parameter: <%= request.getparameter("testparam") %> </UL> </BODY> </HTML> http://149.222.51.81:8180/home-tomcat/jsp/dispert/express.jsp
JSP Expressions
JSP Expressions <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() %> <LI>The <CODE>testParam</CODE> form parameter: <%= request.getparameter("testparam") %> </UL> </BODY> </HTML> http://149.222.51.81:8180/home-tomcat/jsp/dispert/express.jsp?testparam=fh-kiel
JSP Expressions
Scripting: Implicit JSP Objects Scripting request response pagecontext session application out config Implicit JSP Objects.http.HttpServletRequest.http.HttpServletResponse.jsp.PageContext.http.Session.ServletContext.jsp.JspWriter.ServletConfig
Session Example <%@ page errorpage="errorpage.jsp" %> <html> <head> <title>usesession</title> </head> <body> <% // Try and get the current count from the session Integer count = (Integer)session.getAttribute("COUNT"); // If COUNT is not found, create it and add it to the session
Session Example if ( count == null ) { count = new Integer(1); session.setattribute("count", count); } else { count = new Integer(count.intValue() + 1); session.setattribute("count", count); } // Get the User's Name from the request out.println("<b>hello you have visited this site: " + count + " times.</b>"); %> </body> </html> http://149.222.51.81:8180/home-tomcat/jsp/dispert/showsession.jsp
XML XML Syntax
XML Syntax XML Syntax for Expressions: <jsp: expression> Java Expression </jsp: expression> XML Syntax for Scriptlets: <jsp: scriptlet> Code </jsp: scriptlet>
XML Syntax XML Syntax for Declarations: <jsp: declaration> Code </jsp: declaration> XML Syntax for Directives: <jsp: directive.directivetype attribute="value" /> example: <jsp: directive.page import="java.util.*" /> equivalent of: <%@ page import="java.util.*" %>
Applications Starting Applications
Generating Excel Sheets <%@ page contenttype="application/vnd.ms-excel" %> <%-- tabs between columns! --%> 2003 2004 2005 2006 2007 10 20 30 40 50 Tab http://149.222.51.81:8180/home-tomcat/jsp/dispert/excel.jsp
Generating Excel Sheets <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Student Numbers</TITLE> </HEAD> <BODY> <H3>Student Numbers</H3> <% String format = request.getparameter("format"); if ((format!= null) && (format.equals("excel"))) { response.setcontenttype("application/vnd.ms-excel"); } %>
Generating Excel Sheets <TABLE BORDER=1> <TR><TH></TH><TH>SS2007<TH>WS2007/08 <TR><TH>Mult<TD>108<TD>108 <TR><TH>L<TD>272<TD>272 <TR><TH>IuE<TD>668<TD>668 <TR><TH>M<TD>745<TD>745 <TR><TH>B<TD>935<TD>935 <TR><TH>SAG<TD>953<TD>953 <TR><TH>W<TD>1401<TD>1401 </TABLE> </CENTER> </BODY> </HTML> HTML table interpreted by Excel http://149.222.51.81:8180/home-tomcat/jsp/dispert/stdnumb.jsp http://149.222.51.81:8180/home-tomcat/jsp/dispert/stdnumb.jsp?format=excel
Generating Excel Sheets HTML Page http://149.222.57.15:8080/home-tomcat/jsp/dispert/stdnumb.jsp
Generating Excel Sheets Excel Sheet http://149.222.57.15:8080/home-tomcat/jsp/dispert/stdnumb.jsp?format=excel
JSP - Java Server Pages Taglibs
Taglibs Unique feature of JSP: Tag Libraries - Taglibs custom defined JSP tags. used to componentize presentation level logic. similar to Java beans. Basic idea: Every tag is mapped to a particular class file which is executed whenever the tag is encountered in a JSP file. General syntax : <%@ taglib uri = " --- " prefix = " --- " %> JSP-tags can be nested within other tags.
Taglibs Steps to create and use TAGLIBs : 1. create the class file which should implement the Tag and BodyTag interfaces 2. deploy the class file in the Servlet folder of the web server. 3. mapping of a tag to a particular class is done through the use of the file "taglib.tld". The taglib file represents an XML document that defines the tag operation. 4. Tag library is made available to the JSP page using the taglib directive. Ref.: http://jakarta.apache.org/taglibs/tutorial.html
Tag Handler Tag Handler The Tag Handler is responsible for the interaction between the JSP page and additional server-side objects. The handler is invoked during the execution of a JSP page when a custom tag is encountered. Two interfaces describe a tag handler: Tag BodyTag used for simple tag handlers not interested in manipulating their body content an extension of Tagand gives the handler access to its body
Tag Handler The Tag Handler has two main action methods: dostarttag() Process the start tag of this action. doendtag() release() Process the end tag of this action. Called after returning from dostarttag. Release resources
Tag interaction. Container 1: setpagecontext (javax.servlet.jsp.pagecontext):void Tag 2: setparent (javax.servlet.jsp.tagext.tag):void 3: //setattribute:void 4: dostarttag()):int 5: doendtag()):int 6: release()):int
Tag interaction. Container function after page is parsed and a tag is encountered: 1. Use the setpagecontext() method of the Tag to set the current PageContext for it to use. 2. Use the setparent() method to set any parent of the encountered Tag (or null if none). 3. Set any attributes defined to be given to the Tag. 4. Call the dostarttag() method. This method can either return EVAL_BODY_INCLUDE or SKIP_BODY. If EVAL_BODY_INCLUDE is returned, the Tags body will be evaluated. If SKIP_BODY is returned, the Container will not evaluate the body of the Tag. 5. Call the doendtag() method. This method can either return EVAL_PAGE or SKIP_PAGE. IF EVAL_PAGE is returned, the Container will continueto evaluate the JSP page when done with this Tag. If SKIP_PAGE is returned, the Container will stop evaluating the page when it's done with this Tag. 6. Call the release() method. This method can be used by the Tag developer to release any resources that the Tag was using. Please notice thatit is up to the Container to call the release() method when seemed fit, so you can't rely on this method being called at any specific time. In theory, this methodcould be called 12 days after the Tag was used. For this reason, any code that must be executed at the end of the Tag usage should be called from the doendtag() method.
Example: Hello World JSP file: starts with taglib directive <%@ taglib uri = "identifier" prefix = "prefix" %> Location of Tag Library Distinguishes different tag libraries <%@ taglib uri = "/taglib.tld" prefix = "nlib" %> <html> <body> <nlib: Helloworld /> </body> </html>
Tag Library Descriptor Hello World Tag Library Descriptor <?xml version= 1.0 encoding= ISO-8859-1?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglib_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>nlib</shortname> <tag> <name>helloworld</name> <tagclass>mytags.helloworld</tagclass> <body context>empty</body context> </tag> </taglib> tag handler class
Tag class file HelloWorld.class package mytags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagtext.*; public class HelloWorld implements Tag { private PageContext pagecontext; private Tag parent; public int dostarttag() throws JSPException { return SKIP_BODY; } public int doendtag() throws JSPException { try{ pagecontext.getout().write("hello World"); } catch(java.io.exception ex) { throw new JSPException("IO Exception"); } return EVAL_PAGE; } continued
Tag class file continued public void release (){} public void setpagecontext(pagecontext p) { pagecontext=p; } public void setparent(tag t) { parent = t; } } public void getparent() { return parent; } Doku: interface Tag, class PageContext http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/tag.html http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/jsp/pagecontext.html
Tag XML file file "web.xml" (example) describes the mapping between the taglib uri and the location of the Tag Library Descriptor (maps action tags to tag handler classes). taglib-uri <web-app> <taglib> <taglib-uri> http://jakarta.apache.org/taglibs/utilitytags </taglib-uri> <taglib-location> associated with /WEB-INF/tld/utilitytags.tld </taglib-location> </taglib> </web-app> Tag Library Descriptor
Usage JSP directive to tell JSP container to use the URI "/taglib.tld" and the prefix "nlib" <%@ taglib uri = "/taglib.tld" prefix = "nlib" %> Call JSP tag: <nlib:helloworld />
JSTL JavaServer Pages Standard Tag Library The JavaServer Pages Standard Tag Library (JSTL) encapsulates as simple tags the core functionality common to many Web applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags.
Servlet - JSP Comparison Servlet - Java Server Pages
Servlet or JSP? For complex pages, use a combination of both Servlet: get request, validate and process forward() to JSP to generate response dynamically pass information as request attributes Request Servlet URL Browser Response JSP