0% found this document useful (0 votes)
122 views10 pages

JSP - Quick Guide: Java SE Downloads

JSP Quick Reference Guide Quick Help. Commands. Setup. Java Server Pages. Use CGI Common Gateway Interface. Use Java Servelets API

Uploaded by

pilla75
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views10 pages

JSP - Quick Guide: Java SE Downloads

JSP Quick Reference Guide Quick Help. Commands. Setup. Java Server Pages. Use CGI Common Gateway Interface. Use Java Servelets API

Uploaded by

pilla75
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

JSP - QUICK GUIDE

http://www.tuto rialspo int.co m/jsp/jsp_quick_g uide .htm


Co pyrig ht tuto rials po int.co m

What is JavaServer Pag es?


JavaServer Pag es (JSP) is a technolog y for developing web pag es that support dynamic content which helps developers insert java code in HT ML pag es by making use of special JSP tag s, most of which start with <% and end with %>. A JavaServer Pag es component is a type of Java servlet that is desig ned to fulfill the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HT ML or XHT ML code, XML elements, and embedded JSP actions and commands. Using JSP, you can collect input from users throug h web pag e forms, present records from a database or another source, and create web pag es dynamically. JSP tag s can be used for a variety of purposes, such as retrieving information from a database or reg istering user preferences, accessing JavaBeans components, passing control between pag es and sharing information between requests, pag es etc.

Why Use JSP? JavaServer Pag es often serve the same purpose as prog rams implemented using the Common Gateway Interface (CGI). But JSP offer several advantag es in comparison with the CGI. Performance is sig nificantly better because JSP allows embedding Dynamic Elements in HTML Pag es itself instead of having a separate CGI files. JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the targ et script each time the pag e is requested. JavaServer Pag es are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc. JSP pag es can be used in combination with servlets that handle the business log ic, the model supported by Java servlet template eng ines. Finally, JSP is an integ ral part of J2EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding . Setting up JSP Environment
T his step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PAT H environment variable appropriately. You can downloaded SDK from Oracle's Java site: Java SE Downloads. Once you download your Java implementation, follow the g iven instructions to install and config ure the setup. Finally set PAT H and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put the following line in your

C:\autoexec.bat file.
set PATH=C:\jdk1.5.0_20\bin;%PATH% set JAVA_HOME=C:\jdk1.5.0_20

Alternatively, on Windows NT /2000/XP, you could also rig ht-click on My Computer, select Properties, then Advanced, then Environment Variables. T hen, you would update the PAT H value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.5.0_20

Alternatively, if you use an Integ rated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple prog ram to confirm that the IDE knows where you installed Java.

Setting up Web Server: Tomcat


A number of Web Servers that support JavaServer Pag es and Servlets development are available in the market. Some web servers are freely downloadable and T omcat is one of them. Apache T omcat is an open source software implementation of the JavaServer Pag es and Servlet technolog ies and can act as a standalone server for testing JSP and Servlets and can be integ rated with the Apache Web Server. Here are the steps to setup T omcat on your machine: Download latest version of T omcat from http://tomcat.apache.org /. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CAT ALINA_HOME environment variable pointing to these locations. T omcat can be started by executing the following commands on windows machine:
%CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.bat

T omcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-5.5.29/bin/startup.sh

After a successful startup, the default web applications included with T omcat will be available by visiting http://loc alhost:8080/ . If everything is fine then it should display following result:

Further information about config uring and running T omcat can be found in the documentation included here, as well as on the T omcat web site: http://tomcat.apache.org

JSP Processing :
T he following steps explain how the web server creates the web pag e using JSP: As with a normal pag e, your browser sends an HT T P request to the web server. T he web server recog nizes that the HT T P request is for a JSP pag e and forwards it to a JSP eng ine. T his is done by using the URL or JSP pag e which ends with .jsp instead of .html. T he JSP eng ine loads the JSP pag e from disk and converts it into a servlet content. T his conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code that implements the corresponding dynamic behavior of the pag e. T he JSP eng ine compiles the servlet into an executable class and forwards the orig inal request to a servlet eng ine. A part of the web server called the servlet eng ine loads the Servlet class and executes it. During execution, the servlet produces an output in HT ML format, which the servlet eng ine passes to the web server inside an HT T P response. T he web server forwards the HT T P response to your browser in terms of static HT ML content. Finally web browser handles the dynamically g enerated HT ML pag e inside the HT T P response exactly as if it were a static pag e. All the above mentioned steps can be shown below in the following diag ram:

The Scriptlet:
A scriptlet can contain any number of JAVA lang uag e statements, variable or method declarations, or expressions that are valid in the pag e scripting lang uag e. Following is the syntax of Scriptlet:
<% code fragment %>

You can write XML equivalent of the above syntax as follows:


<jsp:scriptlet> code fragment </jsp:scriptlet>

Any text, HT ML tag s, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:
<html> <head><title>Hello World</title></head> <body> Hello World!<br/> <% out.println("Your IP address is " + request.getRemoteAddr()); %> </body> </html>

NO T E: Assuming that Apache T omcat is installed in C:\apache-tomcat-7.0.2 and your environment is setup as per environment setup tutorial. Let us keep above code in JSP file hello.jsp and put this file in C:\apac he-tomc at-7.0.2\webapps\RO O T directory and try to browse it by g iving URL http://localhost:8080/hello.jsp. T his would g enerate following result:

JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. Following is the syntax of JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>

You can write XML equivalent of the above syntax as follows:


<jsp:declaration> code fragment </jsp:declaration>

Following is the simple example for JSP Declarations:


<%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>

JSP Expression:
A JSP expression element contains a scripting lang uag e expression that is evaluated, converted to a String , and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String , you can use an expression within a line of text, whether or not it is tag g ed with HT ML, in a JSP file. T he expression element can contain any expression that is valid according to the Java Lang uag e Specification but you cannot use a semicolon to end an expression. Following is the syntax of JSP Expression:
<%= expression %>

You can write XML equivalent of the above syntax as follows:


<jsp:expression> expression </jsp:expression>

Following is the simple example for JSP Expression:


<html> <head><title>A Comment Test</title></head> <body> <p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> </body> </html>

T his would g enerate following result:

T oday's date: 11-Sep-2010 21:24:25

JSP Comments:

JSP comment marks text or statements that the JSP container should ig nore. A JSP comment is useful when you want to hide or "comment out" part of your JSP pag e. Following is the syntax of JSP comments:
<%-- This is JSP comment --%>

Following is the simple example for JSP Comments:


<html> <head><title>A Comment Test</title></head> <body> <h2>A Test of Comments</h2> <%-- This comment will not be visible in the page source --%> </body> </html>

T his would g enerate following result:

A Test of Comments

T here are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here's a summary:

Syntax <%-- comment --%> <!-- comment --> <\% %\> \' \"

Purpose A JSP comment. Ig nored by the JSP eng ine. An HT ML comment. Ig nored by the browser. Represents static <% literal. Represents static %> literal. A sing le quote in an attribute that uses sing le quotes. A double quote in an attribute that uses double quotes.

JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>

T here are three types of directive tag :

Direc tive <%@ pag e ... %> <%@ include ... %> <%@ tag lib ... %>

Desc ription Defines pag e-dependent attributes, such as scripting lang uag e, error pag e, and buffering requirements. Includes a file during the translation phase. Declares a tag library, containing custom actions, used in the pag e

We would explain JSP directive in separate chapter JSP - Directives

JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet eng ine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another pag e, or g enerate HT ML for the Java plug in. T here is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />

Action elements are basically predefined functions and there are following JSP actions available:

Syntax jsp:include jsp:include jsp:useBean jsp:setProperty jsp:g etProperty jsp:forward jsp:plug in jsp:element jsp:attribute jsp:body jsp:text

Purpose Includes a file at the time the pag e is requested Includes a file at the time the pag e is requested Finds or instantiates a JavaBean Sets the property of a JavaBean Inserts the property of a JavaBean into the output Forwards the requester to a new pag e Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plug in Defines XML elements dynamically. Defines dynamically defined XML element's attribute. Defines dynamically defined XML element's body. Use to write template text in JSP pag es and documents.

We would explain JSP actions in separate chapter JSP - Actions

JSP Implicit Objects:


JSP supports nine automatically defined variables, which are also called implicit objects. T hese variables are:

O bjec ts request response out session application config pag eContext

Desc ription T his is the HttpServletRequest object associated with the request. T his is the HttpServletResponse object associated with the response to the client. T his is the PrintWriter object used to send output to the client. T his is the HttpSession object associated with the request. T his is the ServletContext object associated with application context. T his is the ServletConfig object associated with the pag e. T his encapsulates use of server-specific features like hig her performance

J spWriters . pag e Exception T his is simply a synonym for this , and is used to call the methods defined by the translated servlet class. T he Exc eption object allows the exception data to be accessed by desig nated JSP.

We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.

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 prog ramming including decision making statements, loops etc.

Decision-Making Statements:
T he if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HT ML text included between Scriptlet tag s.
<%! int day = 3; %> <html> <head><title>IF...ELSE Example</title></head> <body> <% if (day == 1 | day == 7) { %> <p> Today is weekend</p> <% } else { %> <p> Today is not weekend</p> <% } %> </body> </html>

T his would produce following result:

T oday is not weekend

Now look at the following switc h...c ase block which has been written a bit differentlty using out.println() and inside Scriptletas:
<%! int day = 3; %> <html> <head><title>SWITCH...CASE Example</title></head> <body> <% switch(day) { case 0: out.println("It\'s Sunday."); break; case 1: out.println("It\'s Monday."); break; case 2: out.println("It\'s Tuesday."); break; case 3: out.println("It\'s Wednesday."); break; case 4: out.println("It\'s Thursday."); break; case 5: out.println("It\'s Friday.");

break; default: out.println("It's Saturday."); } %> </body> </html>

T his would produce following result:

It's Wednesday.

Loop Statements:
You can also use three basic types of looping blocks in Java: for, while,and do.while blocks in your JSP prog ramming . Let us look at the following for loop example:
<%! int fontSize; %> <html> <head><title>FOR LOOP Example</title></head> <body> <%for ( fontSize = 1; fontSize <= 3; fontSize++){ %> <font color="green" size="<%= fontSize %>"> JSP Tutorial </font><br /> <%}%> </body> </html>

T his would produce following result:

JS P Tuto rial

J SP Tutorial

JSP Tutorial
Above example can be written using while loop as follows:
<%! int fontSize; %> <html> <head><title>WHILE LOOP Example</title></head> <body> <%while ( fontSize <= 3){ %> <font color="green" size="<%= fontSize %>"> JSP Tutorial </font><br /> <%fontSize++;%> <%}%> </body> </html>

T his would also produce following result:

JS P Tuto rial

J SP Tutorial

JSP Tutorial

JSP Operators:
JSP supports all the log ical and arithmetic operators supported by Java. Following table g ive a list of all the operators with the hig hest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, hig her precedence operators will be evaluated first.

Categ ory Postfix Unary Multiplicative Additive Shift Relational Equality Bitwise AND Bitwise XOR Bitwise OR Log ical AND Log ical OR Conditional Assig nment Comma

O perator () [] . (dot operator) ++ - - ! ~ */% +>> >>> << > >= < <= == != & ^ | && || ?: = += -= *= /= %= >>= <<= &= ^= |= ,

Assoc iativity Left to rig ht Rig ht to left Left to rig ht Left to rig ht Left to rig ht Left to rig ht Left to rig ht Left to rig ht Left to rig ht Left to rig ht Left to rig ht Left to rig ht Rig ht to left Rig ht to left Left to rig ht

JSP Literals:
T he JSP expression lang uag e defines the following literals: Boolean: true and false Integ er: as in Java Floating point: as in Java String : with sing le and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\. Null: null

You might also like