Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
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
1 / 15
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
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.
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
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.
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
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
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.
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
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.
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
**<% Iterator i = cart.getItems().iterator(); while (i.hasNext()) { ShoppingCartItem item = (ShoppingCartItem)i.next(); BookDetails bd = (BookDetails)item.getItem(); %>
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.
And this is the output. Slide 43
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.
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
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.
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 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" %>
**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
<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"/>
` Use include directive if the file changes rarely
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
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 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
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
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.
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
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.
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
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.
` **Of possible answer these question with help of code. You can make one project for this.
Summary & Questions?
That’s all for today!
58 cs420 Fall 2009-