Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

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)

62 documents

1 / 15

Toggle sidebar

Related documents


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.

JSP Scripting Elements

Lets you insert Java code into the servlet that will be generated from JSP page Minimize the usage of JSP scripting elements in your JSP pages if possible There are three forms Expressions: <%= Expressions %> Scriptlets: <% Code %> Declarations: <%! Declarations %>

Scripting elements let you insert raw Java code into the JSP page directly and this code will be in turn inserted into the Servlet code that will be generated from the JSP page. As was mentioned, the best practice recommendation is not to use scripting elements if possible. Scripting elements can be in 3 different forms ‐ expression, scriptlets, and declarations and they use different syntax as shown in the slide.

Slide 37

Expressions

During execution phase Expression is evaluated and converted into a String The String is then Inserted into the servlet's output stream directly Results in something like out.println(expression) Can use predefined variables (implicit objects) within expression Format

  • <%= Expression %> or // JSP 1.
  • <jsp:expression>Expression</jsp:expression> // JSP2.
  • Semi-colons are not allowed for expressions

A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client. When the scripting language is the Java programming language, an expression is transformed into a statement that converts the value of the expression into a String object and inserts it into the implicit out object. So the end result is like out.println(expression) if you've done it in servlet yourself. The syntax for an expression is as follows. The first is JSP 1.1 syntax and the 2 nd^ one is introduced in JSP 1.2. <%= expression %> <jsp:expression> expression </jsp:expression> Note that a semicolon is not allowed within a JSP expression, even if the same expression has a semicolon when you use it within a scriptlet.

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: <%= application.getServerInfo() %> 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: <% Java code %> or <jsp:scriptlet> Java code</jsp:scriptlet>

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 <% 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 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: 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 2 nd format is supported only in JSP 1.2.

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

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

<%@ include file="filename" %> <%@ 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" %>

jsp:include Element

` Is processed when a JSP page is executed

` Allows you to include either a static or dynamic

resource in a JSP file

**static:** its content is inserted into the calling JSP file dynamic: the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page

` Syntax and example

<jsp:include page="includedPage" /> <jsp:include page="date.jsp"/>

The jsp:include element is processed when a JSP page is executed. The include action allows you to include either a static or dynamic resource in a JSP file. The results of including static and dynamic resources are quite different. If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page. The syntax for the jsp:include element is: <jsp:include page="includedPage" /> The date application introduced at the beginning of this chapter includes the page that generates the display of the localized date with the following statement: <jsp:include page="date.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 <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>

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.

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.

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?**

Summary & Questions?

That’s all for today!

58 cs420 Fall 2009-