Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations

Presentation on theme: "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."— Presentation transcript:

1 JSP and Servelets

2 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

3 Clock example

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

5 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 ( ); out.println ( JSP… ); out.println ( );

6 out.println ( Date and Time ); out.println (new java.util.Date.toString()); out.println ( ); }

7 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

8 JSP directive elements specify page information (static) scripting language, error page includes a file, e.g. an applet declare a tag library (custom actions)

9 JSP and http

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

11 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 ()

12 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

13 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

14 JSP and Java Beans

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

16 Java Beans introspection –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

17 Example Java bean public class ExampleBean implements { 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; }

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

19 JSP action elements action elements –perform an action when page is requested uses a JavaBean component property from JavaBean used in the page sets a JavaBean property (possibly using request information)


21 The following information was saved: User Name: Address:

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

23 JSP and web applications

24 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

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

26 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

27 Tomcat web container Tomcat subdirectories: bin –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)

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

29 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

30 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

31 Creating a web app in NetBeans







38 Adding a JSP to the Web App




42 Running the Web App

43 Browsing the JSP

44 Adding custom tags to a JSP

45 custom tags used to farm out processing to specialised classes or Beans identified by a tag library directive basic JSP tag library –e.g. Apache Taglib custom tag library JavaServerFaces, struts libraries can define your own custom tags

46 custom tags defined as Java classes that extend base classes in javax.servlet.jsp.tagext package represented in a JSP using the syntax – –(can also have element content) custom tag in JSP replaced by code in the servelet on translation

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

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

49 myTags DateStamper myPack.DateStamper empty comment true tag library definition file, myTags.tld

50 deployment in a web application /myTags /WEB-INF/tlds/myTags.tld

51 Tag libraries

52 using the tag in a JSP Using a custom tag Using a custom tag Hello World. My custom tag has the following to say:

53 JSP, Bean and Servelet example

54 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

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

56 football.html Football Search Search the football league table List all games List drawn matches call JSP with a search parameter

57 FootballGame class 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 queryloads DB query result into the FootballGame object

58 FootballSearchBean 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 queriesto use Java Iterator classset up SQL query strings searchType query parameter from football.html ends up here

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

60 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 databasecreate a Statement object (SQL query) to be fired at the DB FootballSearchBean

61 ResultSet r = stmt.executeQuery (request); while ( ()) { 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 FootballSearchBean add the FootballGame to the results Vector

62 League Results Results util package for the Iterator classfootball package with its classes football.jsp Bean created and given an Id searchType property from football.html passed to Bean here

63 No games played yet Results Home Team Home Team Score Away Team Away Team Score searches the database with the user selected search option determines the size of the result set and acts accordingly football.jsp

64 <% Iterator it = (); while (it.hasNext ()) { FootballGame fg = (FootballGame) (); %> creates an Iterator containing FootballGame objects explicit typecast of each object to access the get methods football.jsp use expressions to insert names and scores for each game in table cells

65 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

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

67 FootballServelet PreprocessServelet FootballServelet /FootballInfo

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

69 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); }

70 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); }

71 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 }

72 revised JSP pages // NoResult.jsp ********************************************************** //MatchReport.jsp... <% Iterator it = (); while (it.hasNext ()) { FootballGame fg = (FootballGame) (); %>

73 revised architecture much improved –separation of most of the code from the web designer iterator code still exposed –replace by custom tags from Apache Struts library >...

74 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

Download ppt "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."

Similar presentations

Ads by Google