Dynamic Contents Generation Techniques with JSP-Introduction to Java Programming-Lecture Slides, Slides of Java Programming

This is an Introductory course of Java Web Programming focusing on writing maintainable extensible code, methods of debugging, logging and profiling. The Java Technology used is J2EE an Enterprise Application Development tool. This lecture includes: Dynamic, Content, Generation, JSP, Java, Code, Expressions, Scriptlets, Declerations, Directive, Include, Implicit, Objects, Session, Request, Scope

Typology: Slides

2011/2012

Uploaded on 08/09/2012

dhanyaa
dhanyaa 🇮🇳

4.7

(3)

60 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Dynamic Contents Generation
Techniques with JSP
Call Java code directly within JSP
S
Call Java code indirectly within JSP
S
Use JavaBeans within JSP
S
Develop and use your own custom tags
S
Leverage 3rd-party custom tags or JSTL (JSP
Standard Tag Library)
S
Follow MVC design pattern
S
Leverage proven Model2 frameworks
ThisslidelistsdynamiccontentsgenerationtechniquesthatcanbeusedwithJSPintheorderofitssophistication,from
theleastsophisticatedtothemostsophisticated.Solet'stalkabouttheseinabitmoredetail.
Slide33
(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
TheleastsophisticatedmethodistoplacealltheJavacodewithinaJSPpage.Because,inthismethod,thebusinesslogic
whichisrepresentedinJavacodeandpresentationlogicwhichisrepresentedinJSPpagesareintermixed,itprovides
somewhatweakseparationbetweenthetwo,whichmeansitisratherhardtomaintainandreusethecode.Andweb
pageauthorswillhavedifficulttimetounderstandtheJSPpage.Sothisdesignmodelprovidesonlyaslightlybetter
separationbetweencontentsandpresentationlogicthanservletonlycode.

docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

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 S Call Java code indirectly within JSP S Use JavaBeans within JSP S Develop and use your own custom tags S Leverage 3rd-party custom tags or JSTL (JSP Standard Tag Library) S Follow MVC design pattern S 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.

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

Example: Expressions

Display current time using Date class Current time: <%= new java.util.Date() %> Display random number using Math class Random number: <%= Math.random() %>

Use implicit objects Your hostname: <%= request.getRemoteHost()%> ` Your parameter: <%= request. getParameter(“yourParameter”)%>

Server: &lt;%= application.getServerInfo() %&gt; Session ID: <%= session.getId() %>

These are the examples of expressions. For example, you can use expression to display current time using Java Date class. Or you can display the random number using Math class. Or as was mentioned, you can access all implicit objects such as HttpServletRequest, ServletContext object, and HttpSession objects. Because JSP already defined the names of these implicit objects, you have to use predefined names in your JSP page. For example HttpServletRequest object is represented by request, ServletContext object by application, HttpSession object by session. Slide 39

Scriptlets

Used to insert arbitrary Java code into servlet's jspService() method Can do things expressions alone cannot do setting response headers and status codes writing to a server log updating database executing code that contains loops, conditionals Can use predefined variables (implicit objects) Format: &lt;% Java code %&gt; or Java code

A JSP scriptlet is used to contain any code fragment that is valid for the scripting language used in a page. The syntax for a scriptlet is as follows: <% scripting language statements %> When the scripting language is set to Java programming language, a scriptlet is transformed into a Java programming language statement fragment and is inserted into the service() method of the JSP page's servlet. A programming language variable created within a scriptlet is accessible from anywhere within the JSP page.

Example: Scriptlets

Display query string &lt;% String queryData = request.getQueryString(); out.println(“Attached GET data: “ + queryData); %&gt; 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 2 nd^ 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(); %>

<%=item.getQuantity()%>

<%=bd.getTitle()%>

... <% // 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.

Example: JSP Page fragment

Some heading <%! private String randomHeading() { return(“” + Math.random() + “”); } %> <%= 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. Examples Expression Java code declaration code 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.

Including Contents in a JSP Page

Two mechanisms for including another Web resource in a JSP page include directive ` jsp:include element

There are two mechanisms for including another Web resource in a JSP page: the include directive and the jsp:include element. Slide 47

Include Directive

` Is processed when the JSP page is translated

into a servlet class

` Effect of the directive is to insert the text

contained in another file-- either static content or

another JSP page--in the including JSP page

` Used to include banner content, copyright

information, or any chunk of content that you

might want to reuse in another page

` Syntax and Example

&lt;%@ include file="filename" %&gt; <%@ include file="banner.jsp" %>

The include directive is processed when the JSP page is translated into a servlet class. The effect of the directive is to insert the text contained in another file‐‐ either static content or another JSP page‐‐in the including JSP page. You would probably use the include directive to include banner content, copyright information, or any chunk of content that you might want to reuse in another page. The syntax for the include directive is as follows:

<%@ include file="filename" %> For example, all the bookstore application pages include the file banner.jsp which contains the banner content, with the following directive: <%@ include file="banner.jsp" %>

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 Original request object is provided to the target page via jsp:parameter element

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:

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:

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.

Implicit Objects

request (HttpServletRequest) response (HttpServletRepsonse) session (HttpSession) application(ServletContext) out (of type JspWriter) config (ServletConfig) ` pageContext

The request object is subtype of javax.servlet.ServletRequest. Slide 56

Session, Request, Page Scope

forward (^) forward

request (^) response request response

Page 1 Page 2 (^) Page 3 Page 4

Page scope Page scope Page scope Page scope request scope (^) request scope

Session scope

client

So this picture shows relationship between session, request, and page scopes. Page scope is per page. Request scope spans all the pages that are involved in handling a particular request and session scope includes all the request and responses in a single client specific session.

Assignment 03

` **Of possible answer these question with help of code. You can make one project for this.

  1. How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
  2. How does JSP handle run-time exceptions?
  3. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
  4. How do I use a scriptlet to initialize a newly instantiated bean?
  5. How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
  6. What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
  7. How can I enable session tracking for JSP pages if the browser has disabled cookies?**