Download Dynamic Contents Generation Techniques with JSP-Introduction to Java Programming-Lecture Slides and more Slides Java Programming in PDF only on Docsity! Dynamic Contents Generation Techniques with JSP • Call Java code directly within JSP Call Java code indirectly within JSP Use JavaBeans within JSP Develop and use your own custom tags Leverage 3rd-party custom tags or JSTL (JSP Standard Tag Library) Follow MVC design pattern Leverage proven Model2 frameworks This slide lists dynamic contents generation techniques that can be used with JSP in the order of its sophistication, from the least sophisticated to the most sophisticated. So let's talk about these in a bit more detail. Slide 33 (a) Call Java code directly Place all Java code in JSP page Suitable only for a very simple Web application hard to maintain hard to reuse code hard to understand for web page authors Not recommended for relatively sophisticated Web applications weak separation between contents and presentation The least sophisticated method is to place all the Java code within a JSP page. Because, in this method, the business logic which is represented in Java code and presentation logic which is represented in JSP pages are intermixed, it provides somewhat weak separation between the two, which means it is rather hard to maintain and reuse the code. And web page authors will have difficult time to understand the JSP page. So this design model provides only a slightly better separation between contents and presentation logic than servlet only code. docsity.com (b) Call Java code indirectly Develop separate utility classes Insert into JSP page only the Java code needed to invoke the utility classes Better separation of contents generation from presentation logic than the previous method Better re usability and maintainability than the previous method Still weak separation between contents and presentation, however (c) Use JavaBeans Develop utility classes in the form of JavaBeans Leverage built-in JSP facility of creating JavaBeans instances, getting and setting JavaBeans properties Use JSP element syntax Easier to use for web page authors Better re usability and maintainability than the previous method Now in the next level, you can develop those utility classes in the form of simple component, JavaBeans in this case. Using JavaBeans within a JSP page has an advantage over method (a) and (b) because there is a built‐in support of getting and setting JavaBeans properties in JSP architecture as we will see later on. And because of this built‐in support, accessing JavaBeans from JSP page is a lot easier thing to do for web page authors again compared to method (a) and (b). And because the logic of contents generations is captured in a component form of JavaBeans, the reusability and maintainability increases. docsity.com Slide 40 Example: Scriptlets Display query string <% String queryData = request.getQueryString(); out.println(“Attached GET data: “ + queryData); %> Settng response type <% response.setContentType(“text/plain”); %> This is an example scriptlets. The first example fills the output stream with some query data while in the 2nd example, response type is set through HttpServletResponse implicit object. Slide 41 Example: Scriptlet with Loop <% Iterator i = cart.getItems().iterator(); while (i.hasNext()) { ShoppingCartItem item = (ShoppingCartItem)i.next(); BookDetails bd = (BookDetails)item.getItem(); %> <tr> <td align="right" bgcolor="#ffffff"> <%=item.getQuantity()%> </td> <td bgcolor="#ffffaa"> <strong><a href=" <%=request.getContextPath()%>/bookdetails?bookId= <%=bd.getBookId()%>"><%=bd.getTitle()%></a></strong> </td> ... <% // End of while } %> The JSP page showcart.jsp contains a scriptlet that retrieves an iterator from the collection of items maintained by a shopping cart and sets up a construct to loop through all the items in the cart. Inside the loop, the JSP page extracts properties of the book objects and formats them using HTML markup. Since the while loop opens a block, the HTML markup is followed by a scriptlet that closes the block. docsity.com Slide 42 Example: Scriptlet Result And this is the output. Slide 43 Declarations Used to define variables or methods that get inserted into the main body of servlet class Outside of _jspSevice() method Implicit objects like HttpSession are not accessible to declarations Usually used with Expressions or Scriptlets For initialization and cleanup in JSP pages, use declarations to override jspInit() and jspDestroy() methods Format: <%! method or variable declaration code %> <jsp:declaration> method or variable declaration code </jsp:declaration> Now let's talk about declarations a bit. Declaration is used to to define variables or methods that get inserted into the main body of the resulting servlet class. Please note that these are inserted outside of _jspService() method. So implicit objects such as HttpSession object are not accessible to declarations. Declarations are usually used with expressions or scriptlets. One usage of declaration is for initialization and cleanup in a JSP page. So you can use declarations to override jspInit() or jspDestroy() methods. The format of declarations are shown in the slide, the first format is supported in both JSP 1.1 and 1.2 while the 2nd format is supported only in JSP 1.2. docsity.com Slide 44 Example: JSP Page fragment <H1>Some heading</H1> <%! private String randomHeading() { return(“<H2>” + Math.random() + “</H2>”); } %> <%= randomHeading() %> So in this slide, we have a method declaration example. The declaration of the method called randomHeading() and the usage of it within an expression. Slide 45 Why XML Syntax? From JSP 1.2 Examples <jsp:expression>Expression</jsp:expression> <jsp:scriptlet> Java code</jsp:scriptlet> <jsp:declaration> declaration code </jsp:declaration> You can leverage XML validation (via XML schema) Many other XML tools editor transformer Java APIs Now as shown several times, there are two different syntax or format for JSP elements, one that is being supported from JSP 1.1 and the other, which is compliant with XML syntax, is supported from JSP 1.2. Using XML syntax for JSP element has several advantages. For example, you can use XML validation and many XML tools out there. docsity.com Slide 49 Which One to Use it? Use include directive if the file changes rarely It is faster than jsp:include Use jsp:include for content that changes often Use jsp:include if which page to include cannot be decided until the main page is requested So when do you want use Include directive and when do you want to use include element. The best practice guideline recommends that you use include directive if the included JSP page changes rarely because directive processing is faster than the processing of include element. And use include element when the contents changes often or if the page to include cannot be decided until the main page is requested. Slide 50 Forwarding to another Web component Same mechanism as in Servlet Syntax <jsp:forward page="/main.jsp" /> Original request object is provided to the target page via jsp:parameter element <jsp:forward page="..." > <jsp:param name="param1" value="value1"/> </jsp:forward> The mechanism for transferring control to another Web component from a JSP page uses the functionality provided by the Java Servlet API as described in Transferring Control to Another Web Component. You access this functionality from a JSP page with the jsp:forward element: <jsp:forward page="/main.jsp" /> When an include or forward element is invoked, the original request object is provided to the target page. If you wish to provide additional data to that page, you can append parameters to the request object with the jsp:param element: <jsp:forward page="..." > <jsp:param name="param1" value="value1"/> </jsp:forward> docsity.com Slide 51 Directives Directives are messages to the JSP container in order to affect overall structure of the servlet Do not produce output into the current output stream Syntax – <%@ directive {attr=value}* %> OK, let's talk about directive. Directives are messages (or instruction) to the JSP container. And directives do not produce any output. And the syntax is as shown in the slide. Slide 52 Three Types of Directives page: Communicate page dependent attributes and communicate these to the JSP container – <%@ page import="java.util.* %> include: Used to include text and/or code at JSP page translation-time – <%@ include file="header.html" %> Taglib: Indicates a tag library that the JSP container should interpret – <%@ taglib uri="mytags" prefix="codecamp" %> There are three types of directives. page directive, include directive, and TagLib directive. The page directive is used to communicate page dependent attributes to the JSP container for example importing Java classes. The include directive is used to include text or code at JSP translation time, for example including a HTML page. The TagLib directive indicates a tag library that the JSP container should interpret. docsity.com Slide 53 Page Directives Give high-level information about the servlet that results from the JSP page. Control – Which classes are imported • <%@ page import="java.util.* %> – What MIME type is generated • <%@ page contentType="MIME-Type" %> – How multithreading is handled • <%@ page isThreadSafe="true" %> <%!--Default --%> • <%@ page isThreadSafe="false" %> – What page handles unexpected errors • <%@ page errorPage="errorpage.jsp" %> This slide shows the examples of page directives. For example, you can use directory to specify which Java classes should be imported, what mime types should be generated, how multithreading is handled, and which page handles errors and so on. Slide 54 Implicit Objects A JSP page has access to certain implicit objects that are always available, without being declared first Created by container Corresponds to classes defined in Servlet Implicit objects are created by the Web container transparently and contain information related to a particular request, page, or application. Many of the objects are defined by the Java Servlet technology. docsity.com