JSP and Servelets.

Slides:



Advertisements
Similar presentations
Servlets & JSPs - Sharad Ballepu.
Advertisements

Internet i jego zastosowania 1 J2EE Servlets. Internet i jego zastosowania 2 Agenda Overview Servlet Interface Servlet Context Request Response Sample.
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialitica in Informatica – Università di Trento.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
JSP and web applications
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
M-V-C for web applications. Model for Web Applications model consists of data and system state database tables –persistent data session information –current.
Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.
Cookie in a servlet. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP)
Apache Tomcat as a container for Servlets and JSP
Java Server Pages (JSP)
Java Servlets Java Server Pages (JSP)
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
© Yaron Kanza Advanced Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
Chapter 25 JavaServer Pages and Servlets. CHAPTER GOALS To implement dynamic web pages with JavaServer Pages technology To learn the syntactical elements.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
An introduction to Java Servlet Programming
28/1/2001 Seminar in Databases in the Internet Environment Introduction to J ava S erver P ages technology by Naomi Chen.
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
1 CS6320 – Servlet Cookies L. Grewe 2 What is a cookie? Name-value bindings sent by a server to a web browser and then sent back unchanged by the browser.
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.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Chapter 11 © 2005 by Addison Wesley Longman, Inc Overview of Servlets - A servlet is a compiled Java class - Servlets are executed on the server.
1 Chapter 2 The Web Tier  Web Applications and Web ContainersWeb Applications and Web Containers  Dynamic Content CreationDynamic Content Creation 
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
Jordan Anastasiade. All rights reserved.
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Webcommerce Computer Networks Webcommerce by Linnea Reppa Douglas Martindale Lev Shalevich.
Java Servlets & Java Server Pages Lecture July 2013.
JSP Fundamentals Elements of a JSP Using Beans with JSP Integrating Servlets and JSP.
1 Java Server Pages Allows the embedding of Java commands in a page of HTML. Popular for UI heavy solutions. These commands are then interpreted by a JSP.
Jsp (Java Server Page) Is a server side program.
Java Server Pages An introduction to JSP. Containers and Components Several clients – one system.
JavaServer Page by Antonio Ko. Overview ► Introduction ► What is a servlet? ► What can servlets do? ► Servlets Vs JSP ► Syntax ► Samples ► JavaBean ►
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
ORIGINAL BY WENDY LIU CURRENT API: Java Servlet and JSP 1.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Chapter 3 JSP Overview. The Problem with Servlets processing the request and generating the response are both handled by a single servlet class Java programming.
STRUCTURE OF JSP PRESENTED BY: SIDDHARTHA SINGH ( ) SOMYA SHRIVASTAV ( ) SONAM JINDAL ( )
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
JavaServer Faces framework Craig McClanahan is presented that created Struts web framework and based on experience gathered designed JavaServer.
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
1 Servlets – Part 2 Representation and Management of Data on the Web.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
A Presentation Presentation On JSP On JSP & Online Shopping Cart Online Shopping Cart.
CS 562 Advanced Java and Internet Application Computer Warehouse Web Application By Team Alpha :-  Puja Mehta (102163)  Mona Nagpure (102147)
Handling Errors in Web Applications
Servlets.
Java Servlets By: Tejashri Udavant..
Scripted Page Web App Development (Java Server Pages)
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Pre-assessment Questions
Presentation transcript:

JSP and Servelets

How does JSP work? NOT a Java scripting language NOT like php JSP are NOT parsed on request Java code must involve classes, creation of objects, etc… JSP is a designer-friendly way of writing servlets

Clock example

2 clock.jsp read 1 translation client 3 4 6 request processing 5 GET clock.jsp 1 Server with Tomcat Web Container client Servelet clock.java generate 3 http response 6 clock.class compile and deploy 4 execute 5 request processing

public class clock implements Servlet { public void service (ServletRequest r, ServletResponse s) throws ServletException, IOException { s.setContentType (“text/html”); PrintWriter out = s.getWriter (); out.println (“<HTML>”); out.println (“<HEAD>”); out.println (“<TITLE>JSP… </TITLE>”); out.println (“</HEAD>”); out.println (“<BODY>”);

out.println (“<H1>Date and Time</H1>”); (new java.util.Date.toString()); out.println (“</BODY>”); out.println (“</HTML>”); }

JSP directive elements applied when the JSP is compiled into a servelet Only executed once (on compilation) Do not affect the response Used to set up resources such as Java classes inclusions

JSP directive elements specify page information (static) <%@ page … > scripting language, error page <%@ include … > includes a file, e.g. an applet <%@ taglib … > declare a tag library (custom actions)

JSP and http

JSP and http A JSP is a servelet Permanently resident in server memory Multi-threaded Request and response objects Sessions and cookies

Accessing request information Methods of the request object provide all request information object is called “request” public String getParameter (String name) public String getMethod () public String getHeader (String name) public Cookie [] getCookies ()

javax.servelet.http.Cookie class getName () the name of the cookie getValue(), setValue (String value) gets/sets the value of a cookie getDomain(), setDomain(String dName) get/set the cookie domain name getPath(), String setPath(String path) get/set the request path the cookie is associated with getMaxAge(), setMaxAge (int expiry) get/set maximum age for the cookie

javax.servelet.http.HttpSession provides standard functionality for handling sessions handles cookies as standard but must be extended to handle URL rewriting holds client state info resident in memory automatically times out abandoned sessions created/returned by HttpServeletRequest class getSession method

JSP and Java Beans

Java Beans ordinary Java classes with the following properties: introspection customization events properties persistence

Java Beans introspection properties persistence an analyser can inspect how the Bean works properties naming conventions for getter and setter methods persistence implement the Serializable interface Bean state can be stored

Example Java bean public class ExampleBean implements java.io.Serializable { private String name = null; private int score = 0; public ExampleBean() {} // Empty constructor /* Getter and Setter Methods */ public String getName() { return name; } public void setName(String s) { name = s;

Example Java bean public int getScore() { return score; } public void setScore(int i) { score = i; /* No method required to implement Serializable */

JSP action elements action elements <jsp:useBean> perform an action when page is requested <jsp:useBean> uses a JavaBean component <jsp:getProperty> property from JavaBean used in the page <jsp:setProperty> sets a JavaBean property (possibly using request information)

</jsp:useBean> id="userInfo" class="com.ora.jsp.beans.userInfo.UserInfoBean“ > <jsp:setProperty name = “userInfo” property = “userName” value = “Gandalf” /> </jsp:useBean>

The following information was saved: <ul> <li>User Name: <jsp:getProperty name="userInfo" property="userName"/></li> <li>Email Address: property="emailAddr"/></li> </ul></body></html>

Other JSP action elements <jsp:include> responses from other jsp pages or servelets <jsp:forward> forwards processing to other jsp or servelet <jsp:param> passes a parameter with include or forward <jsp:plugin> generates the HTML to embed an applet

JSP and web applications

Java 2 Enterprise Edition J2EE Edition of Java Architecture specially designed for server-based applications Including web applications Highly compatible with M-V-C Client Tier Middle Tier Enterprise Information System Tier

J2EE Overview EJB Container application EJB EJB Database Web Container JMS JavaIDL RMI JNDI XML servlet servlet browser JSP JDBC JTA/JTS Client Tier Middle Tier EIS Tier

Which J2EE components? Pure JSP Simple applications Prototyping Use M-V-C Business logic pages (model) presentation pages (view) Request processing pages (controller) Enhance with JavaBeans components and custom tags

Tomcat web container Tomcat subdirectories: bin common/lib src conf scripts to run Tomcat common/lib jar archives with javax.servlet class files src interface definitions for javax.servlet classes conf configuration files (Tomcat parameters)

Tomcat web container docs work webapps HTML documentation about Tomcat a working directory for temporary files and generated servlets webapps all web applications run on Tomcat are placed in subdirectories of this

deploying a web application create a subdirectory of webapps, e.g. myDir create a WEB-INF subdirectory of myDir WEB-INF contains web.xml file specifies deployment parameters for the web application lib directory (optional) contains any special class libraries (.jar files) needed .classes directory class files for servlet and helper classes defined for the specific application

the web.xml file written in XML and contains environment data descriptions of servlet names and locations custom tag libraries security constraints on particular servlets multiple url aliases for servlets etc

Creating a web app in NetBeans

Creating a web app in NetBeans

Creating a web app in NetBeans

Creating a web app in NetBeans

Creating a web app in NetBeans

Creating a web app in NetBeans

Creating a web app in NetBeans

Adding a JSP to the Web App

Adding a JSP to the Web App

Adding a JSP to the Web App

Adding a JSP to the Web App

Running the Web App

Browsing the JSP

Adding custom tags to a JSP

custom tags used to farm out processing to specialised classes or Beans identified by a tag library directive basic JSP tag library e.g. <jsp:useBean … /> Apache Taglib custom tag library JavaServerFaces, struts libraries can define your own custom tags

custom tags defined as Java classes that extend base classes in javax.servlet.jsp.tagext package represented in a JSP using the syntax <lib:tag att1=“...” att1=“...” att1=“...” /> (can also have element content) custom tag in JSP replaced by code in the servelet on translation

custom tag example package myPack; import java.util.*; import java.io.*; import javax.servelet.jsp.*; import javax.servelet.jsp.tagext .*; public class DateStamper extends TagSupport { protected String comment = null; public String getComment () { return comment; }

public void setComment (String cm) { comment = cm; } public int doEndTag () { try { String dateStr = (new Date()).toString (); pageContext.getOut ().println ( “<hr>This page entitled, “ + comment + “, was printed on “ + dateStr + “<br>”); catch (Exception e) {//error handling} return EVAL_PAGE; }}

<taglib> <tlibversion>1.0 </tlibversion> <jspversion>1.1 </jspversion> <shortname>myTags</shortname> <tag> <name>DateStamper</name> <tagclass>myPack.DateStamper</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>comment</name> <required>true</required> </attribute> </tag> </taglib> tag library definition file, myTags.tld

deployment in a web application <taglib> <taglib-uri> /myTags </taglib-uri> <taglib-location> /WEB-INF/tlds/myTags.tld </taglib-location </taglib> </web-app>

Tag libraries

using the tag in a JSP <%@ taglib uri=“/myTagLibrary” prefix = “myTags” %> <html><head><title>Using a custom tag</title></head> <body bgcolor = “FFFFFF”> <h1>Using a custom tag</h1> <p>Hello World. My custom tag has the following to say: <myTags:DateStamper comment=“This is a custom tag” /> </body></html>

JSP, Bean and Servelet example

description football league result web application users request match results different requests possible database search html front end user interaction through web-browser servelet/JSP request handling and data processing

system architecture holds a single table Teams containing match data football.jsp highly graphic interactive results page football.html Database handles the request, submits SQL and processes result FootballSearchBean represents football game data contained in a DB table FootballGame static page to request results helper class to create the DB connection DBInfo tomcat

football.html call JSP with a search parameter <html><head><title>Football Search</title></head> <body bgcolor = “white”> <h1>Search the football league table</h1> <ul><li> <a href = “http://localhost:8080/jspeg/football.jsp?searchType=all”> List all games </a> </li><li> <a href = http://localhost:8080/jspeg/football.jsp?searchType=drawn> List drawn matches </a> </li></ul> </body></html> call JSP with a search parameter call JSP with a search parameter

FootballGame class to handle results of data query package football; import java.sql; public class FootballGame { private String team1,team2 private int score1, score2; public String getTeam1 () {return team1;} // similar methods to get team2, score1, score2 public void loadFromResultSet (ResultSet r) throws SQLException { team1 = r.getString (“TEAM1”); // ditto for team2 score1 = r.getInt (“SCORE1”); // ditto for score2 } to handle results of data query loads DB query result into the FootballGame object

FootballSearchBean handle DB queries to use Java Iterator class package football; import java.sql; import java.util; public class FootballSearchbean { private static final allstr = “select * from TEAMS”; private static final drawstr = “select * from TEAMS where SCORE1=SCORE2”; private String searchType; public void setSearchType (String type) { searchType = type; } handle DB queries to use Java Iterator class searchType query parameter from football.html ends up here set up SQL query strings

FootballSearchBean contains results from the DB query private Vector results; public Iterator games () { if (results != null) return results.iterator (); else return null; } public int numGames () { return results.size (); return 0; contains results from the DB query for manipulating retrieved data counts the number of results

FootballSearchBean connect to the database public void doSearch () { results = new Vector (); try { Connection db = DBInfo.connectToDatabase (); Statement stmt = db.createStatement (); String request = allstr; if (“drawn”.equals (searchType)) request = drawstr; // else add code for other search options connect to the database create a Statement object (SQL query) to be fired at the DB

FootballSearchBean ResultSet r = stmt.executeQuery (request); while (r.next ()) { FootballGame fg = new FootballGame (); fg.loadFromResultSet r; results.addElement (fg); } r.close (); stmt.close (); db.close (); } catch (Exception e) {// error-handling code here} fire the query at the DB and store the retrieved rows create a FootballGame object for each retrieved table row add the FootballGame to the results Vector

football.jsp util package for the Iterator class <%@ page import = “java.util.*” %> <%@ page import = “football.*” %> <html><head><title>League Results</title></head><body> <!-- cool and flashy DHTML content inserted here by the web designer. Embedded amongst that will be: --> <h1>Results</h1> <jsp:useBean id = “theLeague” class = “football.FootballSearchBean” /> <jsp:setProperty name = “theLeague” property = “*”/> util package for the Iterator class football package with its classes searchType property from football.html passed to Bean here Bean created and given an Id

football.jsp <% theLeague.doSearch (); %> <% if (theLeague.numGames () == 0) { %> <p> No games played yet </p> <% } else { %> <!-- there are results so set up a table --> <table> <caption>Results</caption> <tr> <th align = “center”>Home Team</th> <th align = “center”>Home Team Score</th> <th align = “center”>Away Team</th> <th align = “center”>Away Team Score</th> </tr> searches the database with the user selected search option determines the size of the result set and acts accordingly

football.jsp creates an Iterator containing FootballGame objects <% Iterator it = theLeague.games (); while (it.hasNext ()) { FootballGame fg = (FootballGame) it.next (); %> <tr> <td><%= fg.getTeam1 () %> </td> <td><%= fg.getScore1 () %> </td> <td><%= fg.getTeam2 () %> </td> <td><%= fg.getScore2 () %> </td> </tr> <% } %> </table> </body></html> creates an Iterator containing FootballGame objects explicit typecast of each object to access the get methods use expressions to insert names and scores for each game in table cells

some design issues Java code in the JSP fragmented through the HTML difficult to trace errors brackets parameter declarations incorrect program logic web designer could unwittingly break the code

revised system architecture Match Report.jsp No Result.jsp football.html Database FootballSearchBean web.xml preprcessing servelet FootballGame hyperlinks now go to a pre-processing servelet DBInfo tomcat

web.xml <web-app> <servelet> <servelet-name>FootballServelet</servelet-name> <servelet-class>PreprocessServelet</servelet-class> </servelet> <servelet-mapping> <url-pattern>/FootballInfo</url-pattern> </servelet-mapping> </web-app>

PreprocessServelet // import all the usual servelet stuff import football.*; public class preprocessServelet extends HttpServelet { private static final String allstr = “no results available yet”; drawstr = “there have been no drawn games”; homestr = “there have been no home wins”; awaystr = “there have been no away wins”; private static final String jspFailPage = “NoResult.jsp”; private static final String jspReportPage = “MatchReport.jsp”;

PreprocessServelet public void doGet () {HttpServeletRequest req, HttpServeletresponse res) throws ServeletException, IOException { String search = req.getParameter (“searchType”); FootballSearchBean fsb = new FootballSearchBean (); fsb.setSearchType (search); fsb.doSearch (); if (fsb.numGames () == 0) { doSearchFail (search, req, res); else doSuccess (fsb, req, res); }

PreprocessServelet private void doSearchFail (String search, HttpServeletRequest req, HttpServeletresponse res) throws ServeletException, IOException { String reason = allstr; if (“drawn”.equals (search)) reason = drawstr; // add similar clauses for other possible reasons req.setAttribute (“Message”, reason); RequestDispatcher d = req.getRequestDispatcher (jspFailPage); d.forward (req, res); }

PreprocessServelet private void doSuccess (FootballSearchBean fsb, HttpServeletRequest req, HttpServeletresponse res) throws ServeletException, IOException { req.setAttribute (“theLeague”, fsb); RequestDispatcher d = req.getRequestDispatcher (jspReportPage); d.forward (req, res); } // end of PreprocessServelet

revised JSP pages // NoResult.jsp <!-- contains the following minimal content --> <jsp:useBean scope=“request” id=“Message” class=“String”> <%= Message %> ********************************************************** //MatchReport.jsp <jsp:useBean scope=“request” id=“theLeague” class=“football.FootballSearchBean”> ... <% Iterator it = theLeague.games (); while (it.hasNext ()) { FootballGame fg = (FootballGame) it.next (); %> <tr><td><%= fg.getTeam1 () %> </td> <!-- etc. -->

revised architecture much improved iterator code still exposed separation of most of the code from the web designer iterator code still exposed replace by custom tags from Apache Struts library <logic:iterate id=“fg” collection=“<%= theLeague.games() >” > <td><bean:write name = “fg” property = “team1” /> ... <!-- HTML and JSP actions to write other cells --> </logic:iterate>

Timetable change From w/c 23/11/09 No Monday Lecture Two lectures moved into one slot: Wednesday 11-1 B39 Labs will still be Thursday, 9-11