Chapter 2

JSP

JSP 2.1 Overview: JSP stands for “Java server page” and built by SUN Microsystem. JSP technology is used to create web application. It focuses more on presentation logic of the web application. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets. Servlet adds HTML code inside Java code while JSP adds Java code inside HTML. Everything a Servlet can do, a JSP page can also do it. JSP enables us to write HTML pages containing tags that run powerful Java programs. JSP separates presentation and business logic as Web designer can design and update JSP pages without learning the Java language and Java Developer can also write code without concerning the web design. JSP Architecture: The web server needs a JSP engine ie., container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs. Following diagram shows the position of JSP container and JSP files in a Web Application.

Fig: Architecture of jsp

JSP Processing: By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

The following steps explain how the web server creates the web page using JSP: i. ii. iii. iv.

v. vi. vii. v. vi.

User requesting a JSP page through internet via web browser. The JSP request is sent to the Web Server. Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet Engine. If the JSP file has been called » the first time then the JSP file is parsed » otherwise servlet is instantiated. The next step is to generate a servlet from the JSP file. [In that servlet, all the HTML code is converted in println statements.] Now, the servlet source code file is compiled into a class file (bytecode file). The servlet is instantiated by calling the init and service methods of the servlet’s life cycle. Now, the generated servlet output is sent via the Internet form web server to user's web browser. Now in last step, HTML results are displayed on the user's web browser. In the end, a JSP is just a Servlet.

Life Cycle: A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet. The following are the paths followed by a JSP  Compilation  Initialization  Execution  Cleanup The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows: JSP Compilation: When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. The compilation process involves three steps:  Parsing the JSP  Turning the JSP into a servlet  Compiling the servlet

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

JSP initialization: When a container loads a JSP it invokes the jspInit() method which is identical in both Java Servlet and applet. It is called first when the JSP is requested and is used to initialize objects and variables that are used throughout the life of the JSP. Syntax:

public void jspInit(){ //Initialization code... }

JSP execution: Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method is automatically and retrieves a connection to HTTP. It will call doGet or doPost() method of servlet created. Syntax: void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... } JSP cleanup: The jspDestroy() method is automatically called when the JSP terminates normally. Override jspDestroy() for cleanup where resources used during the execution of the JSP, such as such as releasing database connections or closing open files. Syntax:

public void jspDestroy{ // Initialization code... }

All the above mentioned steps can be shown below in the following diagram:

Fig: Flow diagram of the JSP life Cycle By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

JSP Operations in Various Scenarios:

2.2 Advantage of JSP over different technologies: Advantage of JSP over Servlet:  Extension to Servlet: JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP that makes JSP development easy.  Easy to maintain JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic.  Fast Development: No need to recompile and redeploy If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application.

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

 Less code than Servlet In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc. Advantages of JSP vs. Active Server Pages (ASP):  First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use.  Second, it is portable to other operating systems and non-Microsoft Web servers. Advantages of JSP Vs PHP[“Hypertext Preprocessor”]:  First, is that the dynamic part is written in Java, which already has an extensive API for networking, database access, distributed objects, and the like, whereas PHP requires learning an entirely new, less widely used language.  A second, is that JSP is much more widely supported by tool and server vendors than is PHP. Advantages of JSP Vs. JavaScript:  JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.

2.3 Basic syntax: JSP tags are an important syntax element of Java Server Pages which start with "<%" and end with "%>" just like HTML tags. Fundamental tags used in Java Server Pages are classified into the following categories:  Comments  Declaration tag  Expression tag  Scriptlet tag  Directive tag  Expression language tag Tags HTML Text

Comments

HTML Comments

Template Text JSP Comment

Description HTML content to be passed unchanged to the client HTML comment that is sent to the client but not displayed by the browser Text sent unchanged to the client. HTML text and HTML comments are just special cases of this. Developer comment that is not sent to the client

By Rama Satish K V, Dept. of MCA

Syntax

Blah

Anything <\% - - - - - %\> <%- - Blah - -%> <%! Blah %> 1 | 46

JSP Directive

Types of Scripting Elements

Chapter 2

JSP

is used within a Java Server page to declare a variable or method that can be JSP referenced by other declarations, Declaration scriptlets, or expressions in a java server page, when page is translated into a servlet. Expression that is evaluated at requested JSP time and sent to the client each time the Expression page is requested. JSP Scriptlet

<%! Field Definition; %> <%! Method Definition;%> Eg:<%! int var = 1; %> <%! int x, y ; %>

<%= Java Value %> Eg:<%=new java.util.Date()%>

<% Java Statement %> Statement or statements that are executed Eg:<% out.println("Your IP each time the page is requested.

address is " + request.getRemoteAddr());%>

page

<%@ directive att="val" %> High-level information about the structure <%@page import="java.util.*"%> of the servlet code

include:

code that is included at page-translation <%@ include file="/header.jsp" %> time.

taglib:

used to use the custom tags in the JSP pages.

<%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>

JSP Expression The purpose of EL is to produce scriptless ${ EL Expression } JSP pages. Language

JSP Action

Action that takes place when the page is requested

..........

Table 2.1: Basic Syntax of JSP Jsp Comments[Creating Template Text]: JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page. There are a special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Syntax

Purpose

<%-- comment --%>

A JSP comment. Ignored by the JSP engine.



An HTML comment. Ignored by the browser.

<\%

Represents static <% literal.

%\>

Represents static %> literal.

\'

A single quote in an attribute that uses single quotes.

\"

A double quote in an attribute that uses double quotes.

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Example 1: Comments.jsp <%-Document : SimpleJsp Created on : Mar 2, 2015, 5:09:35 AM Author : Suma --%> <%@page contentType="text/html" pageEncoding="UTF-8" %> JSP Page

Hello World!

<%-- This comment will not be visible in the page source --%>

Creating Template text: <\% out.println("Hello World"); \%>

Types of JSP Scripting Elements [invoking java code with JSP Scripting element]: JSP scripting elements let you insert Java code into the servlet that will be generated from the JSP page. There are three forms: a. Declaration Tag b. Scriptlet Tag c. Expression Tag (For Definition refer table 2.1) Example 2: Demo <%! int a=2, b=3; %> <%! int sum(int x, int y){ return(x+y); } %>

Demo for Declaration tag

Addition of two values: <%= a+b %>
Addition of two values using function: <%= sum(10,20) %> By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Control-Flow Statements: JSP provides full power of Java to be embedded in your web application. You can use all the APIs and building blocks of Java in your JSP programming including decision making statements, loops etc. Conditional Statements are:  Branching Statements: if, if-else, nested else-if, else-if Ladder, switch  Looping Statements: while, do-while, for, foreach  Jumping Statements: continue, break

Branching / Decision Statements: You can also use all if statements are if, if-else, nested else-if, else-if Ladder, switch in your JSP programming. The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text included between Scriptlet tags. Example 3: Value.html Demo on Conditional Statements
Enter the Value:
CondDemo.jsp [using Scriptlet tag] <%@page="text/html" pageEncoding="UTF-8"%> Check Value using Conditions

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

CondDemo.jsp[ using Scriptlet tag] continued <% String str=request.getParameter("Evalue"); if(str.equals("")) out.println("String is Empty"); else { int i= Integer.parseInt(str); if(i==10) out.println("Entered Value is Equal"); else out.println("Entered Value is not equal"); } %> CondDemo.jsp [Scriptlet is closed at each line with HTML text included between Scriptlet tags] Check Value using Conditions <% String str=request.getParameter("Evalue"); if(str.equals("")) { %>

String is Empty

<% } else { int i= Integer.parseInt(str); if(i==10) { %>

Entered Value is Equal

<% } else { %>

Entered Value is not equal

<% } %>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Output:

Now look at the following switch...case block which has been written a bit differently using out.println() and inside Scriptlet as: Example 4: CondDemo.jsp [switch statement] Check Value using Conditions <% String str=request.getParameter("Evalue"); int i; switch(i=(Integer.parseInt(str)==10)?1:0) { case 0: out.println("Entered Value is not Equal"); break; case 1: out.println("Entered Value is Equal"); break; default: out.println("Entered Proper Input"); } %>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Looping Statements: You can also use three basic types of looping blocks in Java: for, while, and do…while blocks in your JSP programming. Example 5: Value.html Demo on Conditional Statements
Enter the Value:
LoopDemo.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> Looping Page <% String str=request.getParameter("Evalue"); int n=Integer.parseInt(str); int i=1; while(i<=n) { out.println(i+ "
"); i++; } %>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Output:

foreach Statement: The for-each loop is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable. Syntax:

for(data_type variable : array | collection){} Example 6: foreach.html foreachDemo

Select knowing Laguages

C/C++
JAVA/J2EE
JQuery
Python

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

LoopDemo.jsp (Continued) <%@page contentType="text/html" pageEncoding="UTF-8"%> Looping Page

Selected Languages are

<% String[] languages=request.getParameterValues("lang"); for(String l:languages) out.println(l + "
"); %> Output:

Jumping Statements: You can also use jumping statements are break, continue in the JSP Programming. Example 7: index.html Demo on Looping Statements

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Enter the Value:
LoopDemo.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> Looping Page <% String str=request.getParameter("Evalue"); int n=Integer.parseInt(str); int i=1; while(i<=n){ if(i==5) break; else{ out.println(i+ "
"); i++; } } %> Output:

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Invoking Java Code from JSP: There are a number of different ways to generate dynamic content from JSP, as illustrated in the below figure.

 Call Java code directly: Scripting elements calling servlet code directly.  Call Java code indirectly: Scripting elements calling servlet code indirectly (by means of utility classes).

JSP Directives:

 Use beans: Develop separate utility classes structured as beans. Use jsp:useBean, jsp:getProperty etc.  Use the MVC architecture: Have a servlet respond to original request, look up data, and store results in beans. Forward to a JSP page to present results. JSP page uses beans.  Expression Language: Use shorthand syntax to access and output object properties.  Custom tags: Develop tag handler classes. Invoke the tag handlers with XML-like custom tags. Fig: Strategies for invoking dynamic code from JSP.

Each of these approaches has a legitimate place; the size and complexity of the project is the most important factor in deciding which approach is appropriate. However, be aware that people err on the side of placing too much code directly in the page much more often than they err on the opposite end of the spectrum. Although putting small amounts of Java code directly in JSP pages works fine for simple applications, using long and complicated blocks of Java code in JSP pages yields a result that is hard to maintain, hard to debug, hard to reuse, and hard to divide among different members of the development team. For Details, see the following stages.

Limiting java code in JSP: You have 25 lines or more lines of Java code that you need to invoke. You have two options: i. Put all 25 lines directly in the JSP page ii. Put the 25 lines of code in a separate Java class, put the Java class in WEB-INF / classes /directoryMatchingPackageName, and use one or two lines of JSP-based Java code to invoke it. By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Which is better? The second. Here’s Why?  Development: You generally write regular classes in a Java-oriented environment (e.g., an IDE like JBuilder, Eclipse or editor like UltraEdit, emacs). You generally write JSP in an HTML oriented environment like Dreamweaver. The Java-oriented environment is typically better at balancing parentheses, providing tooltips, checking the syntax, colorizing the code, and so forth.  Compilation: To compile a regular Java class, you press the Build button in your IDE or invoke javac. To compile a JSP page, you have to drop it in the right directory, start the server, open a browser, and enter the appropriate URL.  Debugging: We know this never happens to you, but when we write Java classes or JSP pages, we occasionally make syntax errors. If there is a syntax error in a regular class definition, the compiler tells you right away and it also tells you what line of code contains the error. If there is a syntax error in a JSP page, the server typically tells you what line of the servlet (i.e., the servlet into which the JSP page was translated) contains the error. For tracing output at runtime, with regular classes you can use simple System.out.println statements if your IDE provides nothing better.  Division of labor: Many large development teams are composed of some people who are experts in the Java language and others who are experts in HTML but know little or no Java. The more Java code that is directly in the page, the harder it is for the Web developers (the HTML experts) to manipulate it.  Testing: Suppose you want to make a JSP page that outputs random integers between designated 1 and some bound (inclusive). You use Math.random, multiply by the range, cast the result to an int, and add 1. Example:

return(1 + ((int)(Math.random() * range)));

If you do this directly in the JSP page, you have to invoke the page over and over to see if you get all the numbers in the designated range but no numbers outside the range. After hitting the Reload button a few dozen times, you will get tired of testing. But, if you do this in a static method in a regular Java class, you can write a test routine that invokes the method inside a loop and then you can run hundreds or thousands of test cases with no trouble. For more complicated methods, you can save the output, and, whenever you modify the method, compare the new output to the previously stored results.

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Example: public class RanUtilities { /*A random int from 1 to range (inclusive)*/ public static int randomInt(int range) { return(1 + ((int)(Math.random() * range))); } /*Test routine. Invoke from the command line with the desired range. Will print 100 values. Verify that you see values from 1 to range (inclusive)and no values outside that interval.*/

public static void main(String[] args) { int range = 10; try { range = Integer.parseInt(args[0]); } catch(Exception e) { // Array index or number format // Do nothing: range already has default value. } for(int i=0; i<100; i++) { System.out.println(randomInt(range)); } } }

 Reuse: You put some code in a JSP page. Later, you discover that you need to do the same thing in a different JSP page. What do you do? Cut and paste? Boo! Repeating code in this manner is a cardinal sin because if you change your approach, you have to change many different pieces of code. Solving the code reuse problem is what object-oriented programming is all about. Don’t forget all your good OOP principles just because you are using JSP to simplify the generation of HTML. Using Scripting Elements, Comparing servlets and jsp: Example 8: illustrate the difference in how the three JSP scripting elements are typically used by calling the java code indirectly. cssStyle.css body { background-color: #ffdd88; font-family: CurlZ MT, tahoma, helvetica, arial,; font-size: 1.9em; } By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

ScriptletPage.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page <%! int n=5;%> <% for(int i=0;i <%= Corepack.DisplayUtilities.display()%>
<%}%> DisplayUtilities.java package Corepack; public class DisplayUtilities { public static String display() { return("Welcome"); } } Output:

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

In the above example, the goal is to generate a message of n times using scripting elements and compare how the statements are translated into the servlet from the JSP page as shown below. Since the structure of this page is fixed and we use a separate helper class for the display method.  JSP declarations result in code that is placed inside the servlet class definition but outside the _jspService method. Since fields and methods can be declared in any order, it does not matter whether the code from declarations goes at the top or bottom of the servlet.

 JSP Expression result in code that we oversimplified the out variable (which is a JspWriter, not the slightly simpler PrintWriter that results from a call to getWriter).

» JSP expressions basically become

print (or write) statements in the servlet that

results from the JSP page. » Whereas regular HTML becomes print statements with double quotes around the text, JSP expressions become print statements with no double quote.  JSP Scriptlets can perform a number of tasks that cannot be accomplished with expressions alone. These tasks include setting response headers and status codes, invoking side effects such as writing to the server log or updating a database, or executing code that contains loops, conditionals, or other complex constructs. It is easy to understand how JSP scriptlets correspond to servlet code: the Scriptlet code is just directly inserted into the _jspService method: no strings, no print statements, no changes whatsoever.

..... } By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Note: JSP expressions contain Java values and JSP scriptlets contain Java statements.

Controlling the Structure of generated servlets: The JSP page directive: JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form: Syntax:

i.

<%@ directive attribute="value" %>

ii.

<%@ directive attribute1="value1" attribute2="value2" ................ attributeN="valueN" %>

Note:

 Directives can have a number of attributes which you can list down as key-value pairs and separated by commas.  The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional.  To obtain quotation marks within an attribute value, precede them with a backslash, using \’ for ’ and \" for ". In JSP, there are three main types of directives:

i. <%@ page . . . %>

ii. <%@ include . . . %> iii. <%@ taglib . . . %> i.

Let’s you control the structure of the servlet by importing classes, customizing the servlet superclass, setting the content type, and the like. Let’s you insert a file into the JSP page at the time the JSP file is translated into a servlet. defines custom markup tags.

The “page” attribute: The page directive is used to provide instructions to the container that pertain to the current JSP page. The page directive can define one or more of the following attributes and all are case-sensitive: By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2 Sl. No. i.

JSP

Attributes import

Description is used to define a set of class, interface or all the members of a package that must be imported in servlet class definition Syntax:  <%@ page import = "package.class" %>  <%@ page import = "package.class1,......., package.classN" %> Note: By default, the servlet imports following packages : java.lang.*; javax.servlet.*; javax.servlet.jsp.*; javax.servlet.http.*;

For example: Refer Example-a ii.

contentType

Defines the MIME (Multipurpose Internet Mail Extension) type of the HTTP response. Syntax:  <%@ page contentType = “MIME Type" %>  <%@ page contentType = “MIME Type” charset = “Character - Set” %> Note: By default value is "text/html; charset=ISO-8859-1". For example: Refer Example-b

iii.

pageEncoding is used to change the character set. Syntax:  <%@ page pageEncoding=" ISO-8859-1" %> You can change this by specifying US-ASCII, Shift-JIS and etc., For example: Refer Example-b

iv.

session

Specifies whether or not the JSP page participates in HTTP sessions Syntax:  <%@ page session = “true" %>  <%@ page session = “false” %>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP It can have two values: true or false. Default value is true: which means if you do not mention this attribute, server may assume that HTTP session is required for this page. For example: Refer Example-c

v.

isELIgnored

Specifies whether the JSP Expression Language (EL) is ignored (true) or evaluated normally (false). Syntax:  <%@ page isELIgnored = “true" %>  <%@ page isELIgnored = “false” %> //By default false means EL is enabled It can have two values: true or false. Default value is false: which means Expression Language is enabled by default. For example: Refer Example-d

vi.

buffer

specifies the buffer size in kilobytes used by the out variable, which is of type JspWriter. Syntax:  <%@ page buffer = “size kb" %>  <%@ page buffer = “none” %> Note:  Default size is 8Kb  Servers can use a larger buffer than you specify, but not a smaller one. For example: Refer Example-e

vii.

autoFlush

specifies whether the output buffer should be automatically flushed when it is full (the default) or whether an exception should be raised when the buffer overflows ( autoFlush="false"). Syntax:  <%@ page autoFlush = “true" %>  <%@ page autoFlush = “false” %>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP It can have two values: true or false Default value is true : which means automatically flushed when buffered is full For example: Refer Example-e A value of false is illegal when buffer="none" as shown below:  <%@ page buffer=“none”

viii.

info

autoFlush=“false” %>

defines a string that can be retrieved from the servlet by means of the getServletInfo method. Syntax:  <%@ page info = “some message" %> For example: Refer Example-f

ix.

errorPage

is used to define the error page, if exception occurs in the current page, it will be redirected to the another JSP Page by the runtime. Syntax:  <%@ page errorPage = “RelativeURL” %> The exception thrown will automatically be available to the designated error page by means of the exception variable. For example: Refer Example-g

x.

iserrorPage

indicates whether or not the current page can act as the error page for another JSP page. Syntax:  <%@ page isErrorPage = “true” %>  <%@ page isErrorPage = “false” %> It can have two value: true or false Default is false: which means not an error page. For example: Refer Example-g

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2 xi.

isThreadSafe

JSP Servlet and JSP both are multithreaded. You can control that using “isThreadSafe” atttribute. Syntax:  <%@ page isThreadSafe = “true” %>  <%@ page isThreadSafe = “false” %> The default value of isThreadSafe is true. If you make it false, the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a request before passing another request to it. For Example: Refer Example-h

xii.

language

The “language’ attribute is intended to specify the scripting language being used. Syntax:  <%@ page language = “java” %> Default is java. But its support C++, PHP and other Scripting language For Example: Refer Example-i

xiii.

extends

It specifies the superclass of the servlet that will be generated for the JSP page. Syntax:  <%@ page extends= “package.class” %> For Example: Refer Example-i

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Examples for the page directive attributes:

Example-a: <%@page import="java.util.Date" contentType="text/html" pageEncoding="UTF-8"%> Attributes demo

Today Time is: <%= new Date() %>

Output:

Example-b: Welcome.java package JavaPack; public class Welcome { public static String display() { return("Welcome"); } } Contentandpage.jsp <%@page import="java.util.Date,JavaPack.*" contentType="application/msword" pageEncoding="Shift-JIS"%>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Contentandpage.jsp [continued] Attributes demo

Today Time is: <%= new Date() %>

<%= Welcome.display()%> Output:

Example-c: sessionAtt.jsp <%@page import="java.util.Date,JavaPack.*" contentType="text/html" pageEncoding="Shift-JIS" session= "true"%> Attributes demo

Today Time is: <%= new Date() %>

<%= Welcome.display()%>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Output:

Example-d:

ReadEL.html Expression Language
Enter name:

ExprLang.jsp <%@page contentType="text/html" pageEncoding="UTF-8" isELIgnored="true"%> Welcome, ${param.uname}

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Output:

if attribute value is true, then: ignored EL so output as shown below:

Example-e: buffAflush.jsp <%@page import="java.util.Date,JavaPack.*" contentType="text/html" pageEncoding="Shift-JIS" session= "true" buffer="16kb" autoFlush="true"%> Attributes demo

Today Time is: <%= new Date() %>

<%= Welcome.display()%>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Example-f: infoAtt.jsp <%@page import="java.util.Date,JavaPack.*" contentType="text/html" pageEncoding="Shift-JIS" info="Composed by Sonu Nigam"%> Attributes demo

Today Time is: <%= new Date() %>

<%= Welcome.display()%> Output:

Example-g: ErrorDemo.jsp <%@page contentType="text/html" pageEncoding="UTF-8" errorPage="SendError.jsp"%> Error Page Demo <%! int a=0;%> Result: <%= 100/a %> By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

SendError.jsp <%@page contentType="text/html" pageEncoding="UTF-8" isErrorPage="true"%> Caught Error

Sorry an exception occured!


The exception is: <%= exception %>

Output:

If A=2:

If A=0:

Example-h: threadDemo.jsp <%@page import="java.util.Date,JavaPack.*" contentType="text/html" pageEncoding=" UTF-8" isThreadSafe="false"%> Attributes demo

Today Time is: <%= new Date() %>

<%= Welcome.display()%>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Output:

Example-i: <%@page import="java.util.Date,JavaPack.*" contentType="text/html" pageEncoding="Shift-JIS" language="java" extends="org.apache.jasper.runtime.HttpJspBase" %> Attributes demo

Today Time is: <%= new Date() %>

<%= Welcome.display()%>

XML Syntax for Directives: If you are writing XML-compatible JSP pages follow the below syntax:

Example:

<%@ page import="java.util.*" %>

XML equivalent as follows below:

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2 ii.

JSP

The “include” attribute: The include directive tells the Web Container to copy everything in the included file and paste it into current JSP file. Syntax:

<%@ include file="filename.jsp" %>

Example: Welcome.jsp Welcome Page <%@ include file="header.jsp" %> Welcome, User Header.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> This is Header image

Output:

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

iii.

JSP

The “Taglib” directive: The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it will be better to learn it in custom tag. Syntax:

<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example:

<%@ taglib uri="http://www.javapoint.com/tags" prefix="mytag" %>

JSP Action Tags: There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks.

Action Tags

Descriptions

forward

forward the request to a new page

param

Adds parameters to the request

include

Includes a file at the time the page is requested

plugin element

Generates client browser-specific construct that makes an OBJECT or EMBED tag for the Java Applets Defines XML elements dynamically

attribute

defines dynamically defined XML element's attribute

fallback

Supplies alternate text if java applet is unavailable on the client

body

Used within standard or custom tags to supply the tag body.

text

Use to write template text in JSP pages and documents.

getProperty

retrieve a property from a JavaBean instance.

setProperty

store data in JavaBeans instance.

useBean

instantiates a JavaBean

All the above action tag have to write using syntax as mentioned below:

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Syntax:
Attribute= “names” >

i. forward action tag: It is used to forward the request to another resource it may be jsp, html or another resource. Syntax: Without Parameter ” > With Parameter ” > Example: forwardDemo.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page

This is ForwardDemo.jsp



By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

printDate.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page

Print Date Page

Today date is <%= new java.util.Date()%>
<%= request.getParameter("user")%>

Output:

ii. include action tag: This tag is used to include the content of another resource it may be jsp, html or servlet at request time. Syntax: Without Parameter ” > With Parameter ” >

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Example: includeDemo.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page

Demo on include action tag

printDate.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page

Print Date Page

Today date is <%= new java.util.Date()%>
<%= request.getParameter("user")%> Output:

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Difference b/n jsp:include and include directive

include Directive <%@include ----- %>

jsp:include

includes resource at translation time.

includes resource at request time.

better for static pages.

better for dynamic pages.

includes the original content in the generated servlet.

calls the include method.

org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "printDate.jsp" + "?" + rg.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("user", request.getCharacterEncoding())+ "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("suma", request.getCharacterEncoding()), out, false);

iii. “plugin” action tag: It is used to embed applet or bean in the jsp file. The jsp:plugin action tag downloads plugin at client side to execute an applet or bean. Syntax: Applet attributes list below:

Attributes type = "bean/applet"

Description bean or applet object executed by the plugin.

A java class file which has to be executed by the plugin. Extension of this file name must be the .class. Directory name of the Java class file. i.e., directory of code codebase = "classFileDirectoryName" attribute classFileName. code = "classFileName"

align

Specifies the alignment

archive

Specifies the list of archives

height

Specifies the height

width

Specifies the width

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

jreversion

Specifies the version of jre.

hspace

Specifies the horizontal space.

vspace

Specifies the name of vertical space.

name

Specifies the name of component.

nspluginurl iepluginurl

overrides the default url where the plug in can be downloaded. overrides the default url where the plug in can be downloaded.

tags generates the element or tags during the action time. Example: pluginDemo.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page JspPluginApplet.java import import import import

java.awt.*; java.awt.event.*; java.applet.*; java.util.*;

public class JspPluginApplet extends Applet { public void paint(Graphics g){ Calendar cal = new GregorianCalendar(); String hour = String.valueOf(cal.get(Calendar.HOUR)); String minute = String.valueOf(cal.get(Calendar.MINUTE)); String second = String.valueOf(cal.get(Calendar.SECOND)); g.drawString(hour + ":" + minute + ":" + second, 20, 30); } } By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Output:

iv. “fallback” action tags: This element which is used by the client browser in case the plugin cannot be started, that do not support for OBJECT or EMBED. This action cannot be used elsewhere outside the action. Syntax: Message displayed in case of plugin not loaded during the runtime. v. “params” action tags: A jsp:param entries must be enclosed within a “jsp:params” element. This action cannot be used elsewhere outside the action. Syntax: ” > By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Example: pluginDemo.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page Error! plugin not started JspPluginApplet.java import import import import

java.awt.*; java.awt.event.*; javax.swing.JApplet; javax.swing.JLabel;

public class JspPluginApplet extends JApplet { public void init() { label.setHorizontalAlignment(JLabel.CENTER); label.setFont(new Font("Arial", Font.BOLD, 20)); label.setForeground(Color.BLUE); setLayout(new BorderLayout()); add(label, BorderLayout.CENTER); } private JLabel label = new JLabel(); public void start(){ String uname=getParameter("uname"); label.setText("Hello " + uname); } }

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Output:

vi. useBean action tags: Beans are simply Java classes that are written in a standard format( javaBeans API). Following are the unique characteristics that distinguish a JavaBean from other Java classes: ● It provides a default, no-argument constructor. ● It should be serializable and implement the java.io.Serializable interface. ● It may have a number of properties which can be read or written. ● It may have a number of "getter" and "setter" methods for the properties. ● Class must not define any public instance variables.

Advantages:  it is a reusable software component.  A bean encapsulates many objects into one object, so we can access this object from multiple places. Moreover, it provides the easy maintenance.  No Java Syntax

Basic Tasks of useBean: You use three main constructs to build and manipulate JavaBeans components in JSP pages:

This element builds a new bean. Syntax: Example:

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2 jsp:getProperty

JSP This element reads and outputs the value of a bean property. Syntax: Example:

jsp:setProperty

This element modifies a bean property. Syntax: Example:

The setProperty tag is used to store data in JavaBeans instances. The syntax of setProperty tag is or or or

Example: useBeanDemo.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

useBeanDemo.jsp [continued]

Welcome,


Hello,

package bean; import java.io.Serializable; public class PersonBean implements Serializable{ //you should not have public fields and name should be unique private String name; //Default Constructor public PersonBean(){ this.name="RNSIT"; } public void setName(String name){ this.name = name; } public String getName(){ return name; } } Output:

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

Generating Excel Spreadsheet: First Last Email Address Marty Hall [email protected] Larry Brown [email protected] Bill Gates [email protected] Larry Ellison [email protected] <%@ page contentType="application/vnd.ms-excel" %> <%-- There are tabs, not spaces, between columns. --%> Output:

Conditionally Generating Excel Spreadsheet: Attributes demo

List of Names and Address

<% String str=request.getParameter("format"); if(!str.isEmpty()&& str.equals("excel")) response.setContentType("application/vnd.ms-excel"); %>

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2

JSP

FirstLastEmail Address
MartyHall[email protected]
LarryBrown[email protected]
BillGates[email protected]
LarryEllison[email protected]
Output:

Implicit Objects:

Implicit Object

Description

request

The HttpServletRequest object associated with the request.

response

The HttpServletRequest object associated with the response that is sent back to the browser.

out

The JspWriter object associated with the output stream of the response.

session

The HttpSession object associated with the session for the given user of request.

application

The ServletContext object for the web application.

config

The ServletConfig object associated with the servlet for current JSP page.

By Rama Satish K V, Dept. of MCA

1 | 46

Chapter 2 pageContext page exception

JSP The PageContext object that encapsulates the enviroment of a single request for this current JSP page The page variable is equivalent to this variable of Java programming language. The exception object represents the Throwable object that was thrown by some other JSP page.

By Rama Satish K V, Dept. of MCA

1 | 46

AJP-Unit-2-3-JSP.pdf

web application. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of. Servlets. Servlet adds HTML code inside Java code while JSP ...

1MB Sizes 3 Downloads 230 Views

Recommend Documents

No documents