1 / 48

JSP – Java Server Pages Part 2

JSP – Java Server Pages Part 2. Representation and Management of Data on the Internet. Interacting with other Resources. JSP Cooperation. We will consider several ways in which JSP and other resources cooperate Forwarding the request handling to other resources

Download Presentation

JSP – Java Server Pages Part 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JSP – Java Server PagesPart 2 Representation and Management of Data on the Internet

  2. Interacting with other Resources

  3. JSP Cooperation • We will consider several ways in which JSP and other resources cooperate • Forwarding the request handling to other resources • Including the content of other sources • Including the code of other JSP files • Forwarding exception handling to other JSPs

  4. Actions • JSP actionsuse constructs in XML syntax to control the behavior of the Servlet engine • Using actions, you can • forward the request to another resource in the application • dynamically include a resource content in the response

  5. The forward Action • jsp:forward - Forwards the requester to a new resource <jsp:forward page="{relativeURL|<%= expression %>}"> <jsp:param name="parameterName" value="{parameterValue| <%= expression %>}" /> * </jsp:forward> • This action is translated to an invocation of the RequestDispatcher

  6. The include Action • jsp:include- Include a resource content at run time <jsp:include page="{relativeURL|<%= expression %>}">     <jsp:param name="parameterName" value="{parameterValue| <%= expression %>}" />* </jsp:include> • This action is also translated to an invocation of the RequestDispatcher

  7. The include Directive • This directive lets you include files at the time the JSP page is translated into a Servlet • The directive looks like this: <%@ include file="url" %> • JSP content can affect main page • In Tomcat 5.x, generated Servlet is updated when included files change (unlike old versions...)

  8. HTML content Servlet1 Servlet2 HTML content HTML content Include - Action File1.jsp File2.jsp

  9. Servlet HTML content Include Directive File1.jsp File2.jsp

  10. include Action vs. Directive • When a resourceis included using the includeaction, the generated Servlet uses the dispatcher to include its content at runtime • When a file is included using the includedirective, the file itself is included verbatim into the JSP code, prior to the Servlet generation • Question:in which of the above options can the included element change the HTTP headers or status?

  11. BlaBla.jsp <html> <head><title>Including JSP</title></head><body> <h2>Here is an interesting page.</h2> <p>Bla, Bla, Bla, Bla.</p> <%@ include file="/AccessCount.jsp"%> <jsp:include page="/dbimail.jsp"/> </body></html> AccessCount.jsp <%! privateint accessCount = 0; %> <hr><p>Accesses to page since Servlet init: <%= ++accessCount %></p> dbimail.jsp <hr><p> Page Created for Dbi Course at <%= new java.util.Date() %>. Email us <a href="mailto:dbi@cs.huji.ac.il">here</a>. </p>

  12. BlaBla_jsp.java out.write("<html>\r\n"); out.write(" <head><title>Including JSP</title></head>\r\n"); out.write(" <body>\r\n"); out.write(" <h2>Here is an interesting page.</h2>\r\n"); out.write(" <p>Bla, Bla, Bla, Bla.</p>\r\n"); out.write("<hr>\r\n"); out.write("<p> \r\n"); out.write(" Accesses to page since Servlet init: \r\n"); out.print( ++accessCount ); out.write("</p>\r\n"); org.apache.jasper.runtime.JspRuntimeLibrary. include(request, response, "/dbimail.jsp", out, false); out.write(" </body>\r\n"); out.write("</html>\r\n");

  13. Included Counter • Suppose that the file BlaBla2.jsp is similar the BlaBla.jsp • How will the counter ofBlaBla2.jspact? • What if we used a JSP action instead of a JSP directive for the counter?

  14. Error Pages • We can set one JSP page to be the handler of uncaught exceptions of another JSP page, using JSP directives • <%@ pageerrorPage="url " %> • Defines a JSP page that handles uncaught exceptions • The page in url must have true in the page-directive: • <%@ isErrorPage="true|false" %> • The variable exceptionholds the exception thrown by the calling JSP

  15. connect.jsp <html> <head><title>Reading From Database </title></head> <body> <%@ page import="java.sql.*"%> <%@ page errorPage="errorPage.jsp"%> <% Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection ("jdbc:oracle:thin:" + "snoopy/snoopy@sol4:1521:stud"); %> <h2>Connection Established!!</h2> </body> </html>

  16. errorPage.jsp <html> <head><title>Connection Error</title></head> <body> <%@ page import="java.io.*"%> <%@ page isErrorPage="true"%> <h1>Oops. There was an error when you accessed the database.</h1> <h2>Here is the stack trace:</h2> <pre style="color:red"> <% exception.printStackTrace(newPrintWriter(out)); %> </pre> </body> </html>

  17. Custom JSP Tags

  18. Custom JSP Tags • JSP code may use custom tags - tags that are defined and implemented by the programmer • The programmer defines how each of the custom tags is translated into Java code • There are two methods to define custom tags: • Tag libraries - used in old versions of JSP • Tag files - much simpler, introduced in JSP 2.0

  19. Tag Libraries • A tag library consists of: • Tag handlers - Java classes that define how each of the new tags is translated into Java code • A TLD (Tag Library Descriptor) file, which is an XML file that defines the structure and the implementing class of each tag

  20. A Simple TagLib Example DateTag.java package dbi; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; publicclass DateTag extends SimpleTagSupport { publicvoid doTag() throws JspException, IOException { getJspContext().getOut().print(new java.util.Date()); } }

  21. <taglib> <tlib-version>1.0</tlib-version><jsp-version>2.0</jsp-version> <tag> <name>date</name> <tagclass>dbi.DateTag</tagclass> <body-content>empty</body-content> </tag> </taglib> dbi-taglib.tld <%@ taglib prefix="dbitag" uri="/WEB-INF/tags/dbi-taglib.tld" %> <html><body> <h1>Hello. The time is: <dbitag:date/></h1> </body></html> taglibuse.jsp

  22. Tag Files • JSP 2.0 provides an extremely simplified way of defining tags • The idea: for each custom tag, write a tag file tagName.tag that implements the tag translation using JSP code • This way, the programmer can avoid creating tag handlers and TLD files

  23. The Simplified Example date.tag <%= new java.util.Date() %> <%@ taglib prefix="dbitag"tagdir="/WEB-INF/tags/" %> <html> <body> <h1>Hello. The time is: <dbitag:date/></h1> </body> </html> taguse.jsp

  24. Other Capabilities of Custom Tags • Attributes • You can define the possible attributes of the Tags • These can be accessed during the Tag translation • Tag Body • Tag translation may choose to ignore, include or change the tag body

  25. Java Beans in JSP

  26. Motivation • Software components (e.g. objects, data structures, primitives) are extensively used in Web applications • For example: • Service local variables • Attributes forwarded in requests • Session attributes, like users information • Application attributes, like access counters

  27. Motivation • Standard actions are used to manipulate components: declaration, reading from the suitable context, setting of new values (according to input parameters), storing inside the suitable context, etc. • Java Beans provide a specification for automatic handling and manipulation of software components in JSP (and other technologies...)

  28. Java Beans: The Idea • Java Beans are simply objects of classes that follow some (natural) coding convention: • An empty constructor • A readable property has a matching getter • A writable property has a matching setter • Use JSP actions to access and manipulate the bean, and special action attributes to specify the properties of the bean, like its scope

  29. Example 1: Access Counter In the following example, we use a Bean to maintain an access counter for requests to the pages

  30. Counter Bean Bean must reside in a package packagedbi; publicclass CounterBean { privateint counter; publicCounterBean() { counter = 0; } publicintgetCounter() { return counter; } publicvoidsetCounter(int i) { counter = i; } publicvoid increment() { ++counter; } } Bean is created by an empty constructor counter is readable and writable other methods can be used CounterBean.java

  31. <html> <head><title>Bean Example</title></head><body> <jsp:useBean id="accessCounter" class="dbi.CounterBean" scope="application"/> <% accessCounter.increment(); %> <h1> Welcome to Page A</h1> <h2>Accesses to this application: <jsp:getProperty name="accessCounter" property="counter"/> </h2> <a href="pageB.jsp">Page B</a></body> </html> • pageA.jsp invokes getCounter()

  32. <html> <head><title>Bean Example</title></head><body> <jsp:useBean id="accessCounter" class="dbi.CounterBean" scope="application"/> <% accessCounter.increment(); %> <h1> Welcome to Page B</h1> <h2>Accesses to this application: <jsp:getProperty name="accessCounter" property="counter"/> </h2> <a href="pageA.jsp">Page A</a></body> </html> • pageB.jsp

  33. From the Generated Servlet dbi.CounterBeanaccessCounter = null; synchronized (application) { accessCounter = (dbi.CounterBean) _jspx_page_context.getAttribute("accessCounter", PageContext.APPLICATION_SCOPE); if (accessCounter == null) { accessCounter = new dbi.CounterBean(); _jspx_page_context.setAttribute("accessCounter", accessCounter, PageContext.APPLICATION_SCOPE); } }

  34. Example 2: Session Data In the following example, we use a Bean in order to keep a user's details throughout the session

  35. package dbi; public class UserInfoBean { private String firstName; private String lastName; public UserInfoBean() { firstName = lastName = null;} public String getFirstName() {return firstName;} public String getLastName() { return lastName;} public void setFirstName(String string) {firstName = string;} public void setLastName(String string) {lastName = string;} } • UserInfoBean.java

  36. <html> <head><title>Information Form</title></head> <body> <h1>Fill in your details:</h1> <form action="infoA.jsp" method="get"><p> Your First Name: <input type="text" name="firstName" /> <br/> Your Last Name: <input type="text" name="lastName" /><br/> <input type="submit" /></p> </form> </body></html> • infoForm.html

  37. <jsp:useBean id="userInfo" class="dbi.UserInfoBean" scope="session"/> <jsp:setProperty name="userInfo" property="*"/> <html> <head><title>Page A</title></head><body> <h1>Hello <jsp:getProperty name="userInfo" property="firstName"/> <jsp:getProperty name="userInfo" property="lastName"/>, </h1> <h1>Have a nice session!</h1> <h2><a href="infoB.jsp">User Info B</a></h2> </body></html> Match parameters to corresponding properties • infoA.jsp

  38. <jsp:useBean id="userInfo" class="dbi.UserInfoBean" scope="session"/> <jsp:setProperty name="userInfo" property="*"/> <html> <head><title>Page B</title></head><body> <h1>Hello <jsp:getProperty name="userInfo" property="firstName"/> <jsp:getProperty name="userInfo" property="lastName"/>, </h1> <h1>Have a nice session!</h1> <h2><a href="infoA.jsp">User Info A</a></h2> </body></html> • infoB.jsp

  39. Advantages of Java Beans • Easy and standard management of data • Automatic management of bean sharing and lots more • Good programming style • Allow standard but not direct access to members • You can add code to the setters and getters (e.g. constraint checks) without changing the client code • You can change the internal representation of the data without changing the client code • Increase of separation between business logic (written by programmers) and HTML (written by GUI artists)

  40. JSP Expression Language

  41. JSP Expression Language • JSP expression language is a comfortable tool to access useful objects in JSP • This language provides shortcuts in JavaScript-like syntax • An expression in EL is written as ${expr} • For example: Hi, ${user}. <em style="${style}">Welcome</em>

  42. EL Variables • JSP EL does not recognize JSP's implicit objects, but rather has its own set: param, paramValues, header ,headerValues, cookie, initParam, pageScope, requestScope, sessionScope, applicationScope • Each of these objects maps names to values • For example, use param["x"] or param.x to get the value of the parameter x

  43. EL Variables (cont) • A variable that is not an EL implicit object is looked up at the page, request, session (if valid) and application scopes • That is, x is evaluated as the first non null element obtained by executing pageContext.getAttribute("x"), request.getAttribute("x"), etc.

  44. Object Properties • In JSP EL, Property p of Object o is referred to as o[p] • Property p of Object o is evaluated as follows: • If o is a Map object, then o.get(p) is returned • If o is a List or an array, then p is converted into an integer and o.get(p) or o[p] is returned • Otherwise, treat o as a bean, convert p to a string, and return apply the corresponding getter of o • The term o.p is equivalent to o["p"]

  45. An Example <% response.addCookie(new Cookie("course","dbi")); session.setAttribute("dbiurl",new java.net.URL("http://www.cs.huji.ac.il/~dbi/index.html")); String[] strs = {"str1","str2"}; session.setAttribute("arr", strs); %> <html><head><title>JSP Expressions</title></head><body> <form method="get" action="el.jsp"> <h2>Write the parameter x: <input name="x" type="text"/> <input type="submit" value="send"/></h2> </form> </body></html> • elcall.jsp

  46. <%@ page isELIgnored="false"%> <html> <head><title>EL Examples</title></head> <h1>Expression-Language Examples</h1> <h2>Parameter <code>x</code>: ${param["x"]} </h2> <h2>Cookie <code>course</code>: ${cookie.course.value}</h2> <h2>Header <code>Connection</code>: ${header.Connection} </h2> <h2>Path of session attr. <code>dbiurl</code>: ${sessionScope.dbiurl.path}</h2> <h2>Element <code>arr[${param.x}]</code>: ${arr[param.x]} </h2> </body></html> • el.jsp

More Related