JSP Java Server Pages



Similar documents
Services. Custom Tag Libraries. Today. Web Development. Role-Based. Development. Code Reuse. Tag Libraries Custom Tags. Tag Lifecycle.

Server-Side Web Development JSP. Today. Web Servers. Static HTML Directives. Actions Comments Tag Libraries Implicit Objects. Apache.

Complete Java Web Development

Building Web Applications, Servlets, JSP and JDBC

Web Container Components Servlet JSP Tag Libraries

Introduction to J2EE Web Technologies

Controlling Web Application Behavior

Exam Prep. Sun Certified Web Component Developer (SCWCD) for J2EE Platform

In this chapter, we lay the foundation for all our further discussions. We start

Web Programming II JSP (Java Server Pages) ASP request processing. The Problem. The Problem. Enterprise Application Development using J2EE

SSC - Web development Model-View-Controller for Java web application development

Hello World Portlet Rendered with JSP for WebSphere Portal Version 4.1

Outline. CS 112 Introduction to Programming. Recap: HTML/CSS/Javascript. Admin. Outline

Developing XML Solutions with JavaServer Pages Technology

Course Name: Course in JSP Course Code: P5

Creating Java EE Applications and Servlets with IntelliJ IDEA

Class Focus: Web Applications that provide Dynamic Content

Web Application Architecture (based J2EE 1.4 Tutorial)

CrownPeak Java Web Hosting. Version 0.20

Java Server Pages Tutorial

Pure server-side Web Applications with Java, JSP. Application Servers: the Essential Tool of Server-Side Programming. Install and Check Tomcat

DTS Web Developers Guide

Agenda. Summary of Previous Session. Application Servers G Session 3 - Main Theme Page-Based Application Servers (Part II)

Glassfish, JAVA EE, Servlets, JSP, EJB

JBoss Portlet Container. User Guide. Release 2.0

Development. with NetBeans 5.0. A Quick Start in Basic Web and Struts Applications. Geertjan Wielenga

2.8. Session management

Getting Started with Web Applications

Web Pages. Static Web Pages SHTML

SESM Tag Library. Configuring a Tag Library APPENDIX

PA165 - Lab session - Web Presentation Layer

Java 2 Platform, Enterprise Edition (J2EE) Bruno Souza Java Technologist, Sun Microsystems, Inc.

Java Application Developer Certificate Program Competencies

WIRIS quizzes web services Getting started with PHP and Java

Course Information Course Number: IWT 1229 Course Name: Web Development and Design Foundation

A DIAGRAM APPROACH TO AUTOMATIC GENERATION OF JSP/SERVLET WEB APPLICATIONS

PowerTier Web Development Tools 4

CSI 2132 Lab 8. Outline. Web Programming JSP 23/03/2012

PHP and XML. Brian J. Stafford, Mark McIntyre and Fraser Gallop

CS506 Web Design and Development Solved Online Quiz No. 01

Oracle WebLogic Server

Outline. Lecture 18: Ruby on Rails MVC. Introduction to Rails

An introduction to creating JSF applications in Rational Application Developer Version 8.0

Java Server Pages combined with servlets in action. Generals. Java Servlets

Java Web Programming. Student Workbook

Tutorial: Building a Web Application with Struts

JSP. Common patterns

10CS73:Web Programming

Web-JISIS Reference Manual

Efficiency of Web Based SAX XML Distributed Processing

Web Development. Owen Sacco. ICS2205/ICS2230 Web Intelligence

Proposal for DSpace Web MVC

Developing Web Applications using JavaServer Pages and Servlets

Web. Services. Web Technologies. Today. Web. Technologies. Internet WWW. Protocols TCP/IP HTTP. Apache. Next Time. Lecture # Apache.

Accessing Data with ADOBE FLEX 4.6

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

4.2 Understand Microsoft ASP.NET Web Application Development

Modern Web Application Framework Python, SQL Alchemy, Jinja2 & Flask

CONTROLLING WEB APPLICATION BEHAVIOR WITH

Instructor: Betty O Neil

A Guide to Understanding Web Application Development Corey Benson, SAS Institute, Inc., Cary, NC Robert Girardin, SAS Institute, Inc.

Web Presentation Layer Architecture

Building and Using Web Services With JDeveloper 11g

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

Web Frameworks and WebWork

ASP.NET: THE NEW PARADIGM FOR WEB APPLICATION DEVELOPMENT

Software Architecture

The end. Carl Nettelblad

Case Studies of Running the Platform. NetBeans UML Servlet JSP GlassFish EJB

Virtual Credit Card Processing System

Web Service Development Using CXF. - Praveen Kumar Jayaram

Mastering Tomcat Development

White Paper. JavaServer Faces, Graphical Components from Theory to Practice

Short notes on webpage programming languages

JBoss SOAP Web Services User Guide. Version: M5

Course Number: IAC-SOFT-WDAD Web Design and Application Development

T320 E-business technologies: foundations and practice

Web Development in Java Live Demonstrations (Live demonstrations done using Eclipse for Java EE 4.3 and WildFly 8)

WWW. World Wide Web Aka The Internet. dr. C. P. J. Koymans. Informatics Institute Universiteit van Amsterdam. November 30, 2007

Web Application Developer s Guide

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Applets, RMI, JDBC Exam Review

Core Java+ J2EE+Struts+Hibernate+Spring

Chapter 13 Computer Programs and Programming Languages. Discovering Computers Your Interactive Guide to the Digital World

ACM Crossroads Student Magazine The ACM's First Electronic Publication

CS Developing Web Applications with Java Technologies

Drupal CMS for marketing sites

Credits: Some of the slides are based on material adapted from

Advantages of PML as an iseries Web Development Language

}w!"#$%&'()+,-./012345<ya

J2EE Web Development. Agenda. Application servers. What is J2EE? Main component types Application Scenarios J2EE APIs and Services.

Reporting and JSF. Possibilities, solutions, challenges. Slide 1. Copyright 2009, Andy Bosch,

Transcription:

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