1 / 72

JSP – Java Server Pages: The Gory Details

10 fake-points (which aren’t worth anything) to whoever: spots the quote in this slide and names its source Figures out why the container we use is named Apache Tomcat. JSP – Java Server Pages: The Gory Details. Using External Parameters. JSP Initial Parameters.

martha
Télécharger la présentation

JSP – Java Server Pages: The Gory Details

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. 10 fake-points (which aren’t worth anything) to whoever: • spots the quote in this slide and names its source • Figures out why the container we use is named Apache Tomcat JSP – Java Server Pages: The Gory Details

  2. Using External Parameters

  3. JSP Initial Parameters • Like Servlets, initialization parameters can be passed to JSP files using the <servlet> element of the application configuration file web.xml • Use the sub-element <jsp-file> instead of the sub-element <servlet-class> • Since a <servlet> element is being used, a<servlet-mapping> element is also needed • Use the real JSP URL as the <jsp-file> • Remember that just like in servlets mapping, you have the flexibility of being able to map several URLs to the same jsp or servlet, each with different init parameters.

  4. Application scopedinitialization parameters (we haven’t discussed these, but by now you can guess what they do and what they’re good for…) An Example web.xml <web-app> <context-param> <param-name>dbLogin</param-name> <param-value>snoopy</param-value> </context-param> <context-param> <param-name>dbPassword</param-name> <param-value>snoopass</param-value> </context-param>

  5. web.xml <servlet> <servlet-name>ParamPage</servlet-name> <jsp-file>/paramPage.jsp</jsp-file> <init-param> <param-name>tableName</param-name> <param-value>users</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ParamPage</servlet-name> <url-pattern>/paramPage.jsp</url-pattern> </servlet-mapping> </web-app> In the case of JSP, the relative location of the JSP (relative to the application’s root directory)should be given instead of the Servlet classname since the Servlet is created from it by the container. JSP scoped initialization parameters You can also map a different URL to this JSP (highly useful if you need the URL to end with an extension other than .jsp)

  6. paramPage.jsp You can omit the config and call getInitParameter() directly, since the generated servlet extends HttpJspBase which extends HttpServlet which implements the ServletConfig interface <html> <head><title>JSP initial parameters</title></head> <body> <h1>Hello</h1> <h2>I should use the table <i><%= config.getInitParameter("tableName") %></i> </h2> <h2>To access the Database, I should use the login <i><%= application.getInitParameter("dbLogin") %></i> and the password <i><%= application.getInitParameter("dbPassword") %></i>. </h2> </body> </html> JSP scoped initialization parameters Application scoped initialization parameters Reminder: within a JSP this is Equivalent to getServletContext().getInitParameter() within a Servlet

  7. Interacting with other Resources

  8. 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

  9. 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 A Quick Reference to JSP Elements

  10. 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> • Can you write down the code this translates to? • Hint: Recall RequestDispatcher from last week 0 or more parameters (not attributes!) added to the original request parameters You can use %=, % instead of <%=, %> so that the code would be a legal XML The forward action

  11. Forward Action Example <%! int even = 0; %> <% even = (1 - even); %> <% if (even == 0) { %> <jsp:forward page="/requestParams.jsp" > <jsp:param name="sessionID" value="<%= session.getId() %>" /> <jsp:param name="even" value="true" /> </jsp:forward> <% } else { %> <jsp:forward page="/requestParams.jsp" > <jsp:param name="sessionID" value="<%= session.getId() %>" /> <jsp:param name="even" value="false" /> </jsp:forward> <% } %> forward.jsp

  12. <html> <head><title>Print Request Params</title></head> <body> <%@ page import="java.util.*" %> <% Enumeration parameterNames = request.getParameterNames(); %> <% while (parameterNames.hasMoreElements()) { %> <% String name = (String)parameterNames.nextElement(); %> <h2><%= name %> : <%= request.getParameter(name) %> </h2> <% } %> </body> </html> requestParams.jsp Open /forward.jsp?year=2006

  13. 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 0 or more parameters added to the original request parameters The include action

  14. Include Action Example <html> <head> <title>Include (action) Example</title> </head> <body> <h2>Included part begins:<h2><hr/> <jsp:include page="/requestParams2.jsp" > <jsp:param name="sessionID" value="<%= session.getId() %>" /> </jsp:include> <hr/><h2>Included part ends<h2> </body> </html> include.jsp

  15. <%@ page import="java.util.*" %> <% Enumeration parameterNames = request.getParameterNames(); %> <% while (parameterNames.hasMoreElements()) { %> <% String name = (String)parameterNames.nextElement(); %> <h2><%= name %> : <%= request.getParameter(name) %> </h2> <% } %> requestParams2.jsp The html tags were removed. Otherwise the main JSP output HTML code would have 2 html elements for example… Open /include.jsp?year=2006

  16. 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" %> • Included JSP content can affect main JSP page • e.g. included page directive can affect the result ContentType • As of Tomcat 5.x, generated Servlets are updated when included files change (unlike older versions...) The include directive

  17. HTML content Servlet1 Servlet2 HTML content HTML content Main JSP Include - Action Using RequestDispatcher File1.jsp File2.jsp

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

  19. include Action vs. Directive • When a resourceis included using the includeaction, the generated Servlet uses the dispatcher to include its content at runtime (so the resource needs not be a JSP or even a Servlet) • When a file is included using the includedirective, the file itself is included verbatim into the JSP code, prior to the Servlet generation (so the included resource must have JSP syntax) • In which of the above cases can the included resouce change the HTTP headers or status? Compare the results of includeaction.jsp, includedirective.jsp

  20. 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>

  21. 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"); Original JSP Included JSP Similar to RequestDispatcher().include() Original JSP

  22. Directive Included Counter • Suppose that the file BlaBla2.jsp is similar the BlaBla.jsp • How will the counter ofBlaBla2.jspact? Why? • Will it be identical to the 1st counter or • What if we used a JSP action instead of a JSP directive for the counter? • Will it be to the 1st counter or not? Why? not? identical

  23. Error Pages • We can set one JSP page to be the handler of uncaught exceptions of another JSP page, using JSP directives • The default behaviour is displaying a500 Internal Server Error with a partialstack trace with other exception infoto the client (ugly and a security risk). • You can log the entire stack trace alongwith other data for easier debugging • <%@ pageerrorPage="url " %> • Defines a JSP page that handles uncaught exceptions • The page in url should have true in the page-directive: • <%@ page isErrorPage="true|false" %> • The variable exceptionholds the exception thrown by the calling JSP Runtime exceptions or other exceptions which are declared as thrown by methods your JSP code use.Other exceptions cannot be thrown or else your generated servlet code wouldn’t compile Creating an error page without isErrorPage=true, is legal but the exception object is not created in the generated Servlet.If you refer to exception in such a JSP, you’ll have a compilation error…

  24. connect.jsp <html> <head><title>Reading From Database </title></head> <body> <%@ page import="java.sql.*"%> <%@ page errorPage="errorPage.jsp"%> <% Class.forName("org.postgresql.Driver"); Connection con = DriverManager.getConnection ("jdbc:postgresql://dbserver/public?user=" + "snoopy"); %> <h2>Can Connect!!</h2> </body> </html> • Reminder: • The driver is loaded dynamically • Creates an instance of itself • Register this instance with the DriverManager

  25. 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> A method of any exception object (and not a JSP special method) that prints the stack trace into a given PrintWriter.In our case, the PrintWriter is the out implicit object. If you want to sleep better at night, flush the PrintWriter before continuing (why, if we aren’t using out anymore?)

  26. This is the result you’ll see if the server can find the driver package, and connect to the database using the driver created with user=snoopy

  27. This is the result you’ll see if the server can find the driver package, but fails to connect to the database using the driver created with user=snoopy Check the result of calling connect2.jsp which raises an exception after trying to load a non-existing class This time the error page is errorPage2.jsp in which isErrorPage=true is missing…

  28. Custom JSP Tags

  29. 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

  30. 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 Tag Libraries tutorial The taglib directive

  31. A Simple TagLib Example • Goal: <dbitag:date/> We must use a package (not necessarily named like your application) since this is a helper class which is imported form the JSP’s generated Servlet that is placed within a named package The java file is placed in webapps/dbi/WEB-INF/src/dbi/ The class file is placed in webapps/dbi/WEB-INF/classes/dbi/ 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()); } } Base class of tags which don’t handle the body or the attributes Using the JSP-context, You can also acquire other implicit objects by calling getSession(), getRequest() etc… Read more about SimpleTagSupport Class

  32. <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> Set this value that indicates your tag library version Name of the tag Tag’s class file in /dbi/WEB-INF/classes/dbi/ This defined tag contains no body The prefix for this tag must appear before the tag itself (looks like a namespace). The Prefix can’t be empty You can add here more tags… 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> As you can see from the path, the taglib is specifically defined to the current application context. taglibuse.jsp The path could be a URL. If you choose to use a local path, it must begin with /WEB-INF/tags/

  33. Taglib with Attributes Base class of tags which do handle attributes package dbi; importjavax.servlet.jsp.JspException; importjavax.servlet.jsp.tagext.TagSupport; importjava.io.IOException; public class DateTag2 extendsTagSupport { private booleanisLongFormat = false; public void setIsLongFormat(boolean b) { isLongFormat = b; } public boolean getIsLongFormat() { returnisLongFormat; { In our example the attribute is defined as not required so it must have a default value The setter/getter methods should be named after the attribute (i.e. “get” + capital (<attribute>)) This member’s name should be identical to the attribute’s. Attribute’s setter method Attribute’s getter method DateTag2.java

  34. Invoked when the generated Servlet starts processing the “start tag” public int doStartTag() throwsJspException { try{ if(isLongFormat) { pageContext.getOut().print(new java.util.Date().getTime()); } else{ pageContext.getOut().print(newjava.util.Date()); } } catch(Exceptione) { throw newJspException("DateTag: " + e.getMessage()); } returnSKIP_BODY; } public intdoEndTag() { returnEVAL_PAGE; } } Prints the date according to the isLongFormat attribute Signals the generated Servlet there’s no body within the tag to process Invoked when the generated Servlet starts processing the “end tag” Signals the generated Servlet to continue executing the generated Servlet code Read more about TagSupport Class

  35. Same as before, only with different names for the tag,class <tag> <name>date2</name> <tagclass>dbi.DateTag2</tagclass> <body-content>empty</body-content> <attribute> <name>isLongFormat</name> <required>false</required> </attribute> </tag> You can put several blocks one after another The attribute is “not required” so you have to define a default value in DateTag2.java dbi-taglib2.tld <%@ taglib prefix="dbitag" uri="/WEB-INF/tags/dbi-taglib2.tld" %> <html><body> <h1>Hello.</h1> <h2>The time is: <dbitag:date2/></h2> <h2>Milliseconds since the epoch : <dbitag:date2 isLongFormat="true" /></h2> </body></html> Uses default attribute value Uses a given attribute value taglibuse2.jsp

  36. How does it work? taglibuse2.jsp taglibuse2_jsp.java Create the JspContext When the translation engine first encounters <dbitag:date2> it creates a new instance of DateTag2 (so we needn’t worry about concurrency issues) and passes it the JspContext reference JspContext JSP to Java Servlet translation DateTag2setIsLongFormat() doStartTag() doEndTag() The attribute value is set using the setter method. The translator actually translated the attribute string value as it appears in the JSP source, to a boolean value as the Java tag class expects it… “Start tag” is reached “End tag” is reached

  37. Tag Files • JSP 2.0 provides an extremely simplified way of defining tags • The movitation: JSP programmers don’t like writing cumbersome code or class files. • 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

  38. 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> In this new mechanism we use tagdir instead of uri we used in the old taglib implementation taguse.jsp

  39. A new directive The Attributes Example <%@ attribute name="isLongFormat" required="false" %> <%!private String createDate(String isLong) { if ((isLong == null) || (isLong.equals("false"))) { return new java.util.Date().toString();} else { return new Long(new java.util.Date().getTime()).toString();} } %> <%=createDate(isLongFormat)%> date3.tag Default and isLongFormat=“false” case Private method declaration isLongFormat=“true” case Calls the private method The isLongFormatparameter is identified as the isLongFormat attribute because we used the attribute directive <%@ taglib prefix="dbitag" tagdir="/WEB-INF/tags/" %> <html><body> <h1>Hello.</h1> <h2>The time is: <dbitag:date3/></h2> <h2>Milliseconds since the epoch : <dbitag:date3 isLongFormat="true" /></h2> </body></html> Default case isLongFormat=“true” taguse3.jsp

  40. Other Capabilities of Custom Tags • Attributes • You can add validation mechanism for the attributes values • Tag Body • Tag translation may choose to ignore, include or change the tag body

  41. Java Beans in JSP Read more about JavaBeans The useBean action The setProperty action The getProperty action

  42. 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

  43. 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...)

  44. 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 • JSP programmers don’t like writing cumbersome code or class files.

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

  46. A Bean is a concept and therefore there’s no need to extend any class or implement any interface! (though it would’ve been very Java-ish to create an empty interface “Bean”) Bean must reside in a package Counter Bean packagedbi; publicclass CounterBean { privateint counter; publicCounterBean() { counter = 0; } publicintgetCounter() { return counter; } publicvoidsetCounter(int i) { counter = i; } publicvoid increment() { ++counter; } } A Bean is created by an empty constructor Counter setter and getter Other methods can be implemented as well CounterBean.java

  47. The default scope is page <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> You could also use the type attribute in order to instantiate a data type which is either superclass of class or an interface that class implements An instance named according to the given id is either found in the right scope or created.Any tags inside <jsp:useBean> will be executed on instantiation only (but not if the instance is already an attribute of the right scope) • pageA.jsp Invokes getCounter()

  48. <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> Since an instance named according to the given id can be found in the application scope, no instantiation takes place • pageB.jsp A very similar JSP

  49. From the Generated Servlet The instance is created and kept in the application’s scope as required. Note however that accessing this instance is out of the synchronized scope 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); } } Similar effect to getServletContext().getAttribute() Similar effect to getServletContext().setAttribute()

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

More Related