CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP) JavaServer Pages (JSP) Why JSP? • Get rid of Java programming. • Separate presentation from business logic. • Reuse predefined components, such as JavaBean, tag libraries. How does JSP work? • The entire JSP page gets translated into a Servlet (once) at the first time it is invoked. • It is the Servlet code that gets executed at each request. No interpretation of JSP occurs at request time. The original JSP page is totally ignored at request time. JSP tutorial website: http://www.jsptut.com/ http://java.sun.com/products/jsp/docs.html 2 Example of a Translated JSP The original JSP <H1>A Random Number</H1> <%= Math.random() %> The resulting Servlet code public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println("<H1>A Random Number</H1>"); out.println(Math.random()); ... } 3 JSP Notations JSP can include Java code, applets, servlets, JavaBeans, etc. • JSP Expressions: <%= expression %> • JSP Scriptlets (for Java code): <% Java-code %> • JSP Declarations: <%! declarations %> • JSP Directives: <%@ directive %> e.g., <%@ page import = “java.util.*”%> <%@ include file = “banner.html”%> 4 The First JSP example • JSP files in dir: ~jia/www/java/js/jsp/ • URL for run JSP: http://jserv.cs.cityu.edu.hk:8080/jia/jsp/jspDate.jsp <%-- file: ~jia/www/java/js/jsp/jspDate.jsp--%> <html> <head><title> Simple JSP Test Page</title></head> <body> <h1 align=center>Simple JSP Test Page</h1> <table align=center> <tr> <td> Now, the time is: </td> <td> <%= new java.util.Date() %> </td> </tr> </table> </body></html> 5 An Example of JSP Scriptlets (Java code) <HTML> <BODY> The time returned from a java utility function: <% // This scriptlet declares and initializes "date" java.util.Date date = new java.util.Date(); out.println( date ); out.println( "<BR>Your machine's address is " ); // request in next line is in servlet style out.println( request.getRemoteHost()); %> </BODY> </HTML> 6 An Example of JSP Declaration and Directives <%-- the next line is a JSP directive --> <%@ page import="java.util.*" %> <HTML> <BODY> <!-- following is a JSP declaration of function getDate --> <%! Date getDate() { Date theDate = new Date(); return theDate; } %> <!-- the next line has JSP expression --> The time returned from java declared function is: <%= getDate() %> </BODY> </HTML> 7 Another Example of Scriptlet <%-- filename: welcome.jsp --%> <html><head> <title>Example of JSP Scriptlet</title> </head> <body> <% // begin scriptlet String name = request.getParameter( "firstName" ); if ( name != null ) { %> <h1>Hello <%= name %>, <br /> Welcome to JavaServer Pages!</h1> <% // continue scriptlet } // end if else { %> <form action = "welcome.jsp" method = "GET"> <p>Type your first name and press Submit</p> <p><input type = "text" name = "firstName" /> <input type = "submit" value = "Submit"/> </p> </form> <% // continue scriptlet } // end else %> <%-- end scriptlet --%> </body> </html> 8 JSP Directives JSP directives are used for specifying page settings at translation time. Three directives: page, include, and taglib. • page directive: define the page setting. e.g., <%@ page import = “java.util.*”%> • include directive: insert a file at translation-time as if it were originally part of the JSP (note. jsp:include inserts a file at request time!). e.g., <%@ include file = “banner.html”%> • taglib directive: specify user-defined tag libraries. e.g., <%@ taglib prefix=”blx” uri=”/blx.tld” %> 9 JSP Standard Actions JSP actions allow some common tasks in JSP. JSP containers process actions at request time: • <jsp:include>. Include a file at request time (Note. The include directive inserts a file at translation time) e.g., <jsp:include page = “banner.html”> • <jsp:forward>. Forward the processing to another JSP or servlet. This terminates the current JSP’s execution. e.g., <jsp:forward page = “errorProcess.jsp”> • <jsp:plugin>. Allow a browser-object (applets) or html element embedded in jsp. It’s passed to browser without being executed in server! e.g., <jsp:plugin type="applet" code=“myApplet.class” width="475" height="350"></jsp:plugin> 10 JSP Standard Actions (Cont.) • <jsp:param>. Pass parameters to another JSP or servlet (used together with include, forward, and plugin). • <jsp:useBean>. Specify scope of a JavaBean and assign id. e.g. <jsp:useBean id="numguess" class="num.NumberGuessBean" scope="session"/> The next two actions are used with JavaBean instance: • <jsp:setProperty> • <jsp:getProperty> 11 Example of jsp:forward and jsp:param <%-- filename: forwardExample.jsp --%> <html><head> <title>Forward request to another JSP</title> </head> <body> <% // begin scriptlet String name = request.getParameter( "firstName" ); if ( name != null ) { %> <jsp:forward page = "forwardJSP.jsp"> <jsp:param name = "date" value = “<%= new java.util.Date() %>”/> </jsp:forward> <% } // end if else { %> <form action = "forwardExample.jsp" method = "GET"> <p>Type your first name and press Submit</p> <p><input type = "text" name = "firstName" /> <input type = "submit" value = "Submit"/></p> </form> <% } // end else %> </body> </html> 12 Example of JSP: forward and jsp:param (Cont.) <%-- filename: forwardJSP.jsp --%> <html> <head> <title>Processing a jsp:forward request</title> </head> <body> <p> Hello <%= request.getParameter( "firstName" ) %>, <br /> Your request was received <br /> and forwarded at <%= request.getParameter( "date" ) %> </body> </html> 13 Example of JSP: useBean The program numguess.jsp uses a JavaBean object NumberGuessBean.class, which is in …/js/WEB-INF/classes/num. See NumberGuessBean.java for lib routines. <%@ page import ="num.NumberGuessBean"%> <jsp:useBean id="numguess" class="num.NumberGuessBean" scope="session"/> <jsp:setProperty name="numguess" property="*"/> <html> <head><title>Number Guess</title></head> <body bgcolor="white"> <% if (numguess.getSuccess()) { %> Congratulations! You got it. And after just <%= numguess.getNumGuesses() %> tries.<p> <% numguess.reset(); %> Would you <a href="numguess.jsp"> try again</a>? <% } else if (numguess.getNumGuesses() == 0) { %> Welcome to the Number Guess game.<p> I‘ve a number between 1 and 100.<p> <form method = GET> What's your guess? <input type=text name = guess> <input type=submit value="Submit"> </form> ….</body> </html> 14 Example of JSP Tag Library (taglib) Directive taglib allows user defined tags, facilitating the use of large amount of Java libraries in jsp (separate JSP from Java-code implementations). Three files involved for taglib: 1. JSP file, specifying the use of taglib, e.g., SendMail.jsp: <%@ taglib prefix=“send" uri=“./taglib.tld" %> // “send” is prefix you can use <HTML><BODY> <% String email = request.getParameter( "email" ); %> <send:email host="yoursmtphost.com" from="you@email.com"> <blx:emailTo><%= email %></blx:emailTo> </send:email> 2. Tag Library Descriptor file (.tld) in XML format, taglib.tld, specify format of lib routines, such as routine names, parameters, etc.: <tag><name>Sendmail</name> <tagclass>com.cj.smtp.Sendmail</tagclass> <teiclass>com.cj.smtp.BoolVariable</teiclass> ………… 3. Library routines (java class file), sendmail.jar in …WEB-INF/lib (for you only) or jserv:/usr/jt/lib (for all users). See dir setting in http://www.jsptube.com/servlet-tutorials/web-application-directorystructure.html Use “jar –tvf blazix.jar” cmd to see the list of routines in class file. 15 JSP JDBC Example <%@ page contentType="text/html;charset=utf-8"%> <%@ page import="java.sql.*" %> <HTML><HEAD> <TITLE>JSP JDBC</TITLE></HEAD> <BODY> <center>JSP JDBC</center> <BR><BR> <table border=3 align=center > <% Class.forName("com.mysql.jdbc.Driver"); String url = “jdbc:mysql://jserv.cs.cityu.edu.hk:3306/db_jdemo”; Connection con= DriverManager.getConnection(url, "jdemo","apple1"); Statement stmt=con.createStatement(); String sql="select COF_NAME, PRICE from COFFEES"; ResultSet rs=stmt.executeQuery(sql); while(rs.next()) { out.print("<TR><TD>"+ rs.getString("COF_NAME")+"</TD>"); out.print("<TD>"+ rs.getString("PRICE")+"</TD></TR>"); } %> </table> <BR><HR> <% rs.close(); stmt.close(); con.close(); %> </BODY> </HTML> 16