JSP Tutorial
JSP Tutorial
JSP Tutorial
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages 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 target script each time the page is requested. JavaServer Pages 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 pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
Finally, JSP is an integral 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.
1|Page
Download latest version of Tomcat 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/apachetomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.
%CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$CATALINA_HOME/bin/startup.sh or
2|Page
Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server. The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html. The JSP engine loads the JSP page from disk and converts it into a servlet content. This 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 page. The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response. The web server forwards the HTTP response to your browser in terms of static HTML content. Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
3|Page
The Scriptlet:
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. Following is the syntax of Scriptlet:
<html> <head><title>Hello World</title></head> <body> Hello World!<br/> <% out.println("Your IP address is " + request.getRemoteAddr()); %> </body> </html>
NOTE: Assuming that Apache Tomcat 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:\apache-tomcat7.0.2\webapps\ROOT directory and try to browse it by giving URL http://localhost:8080/hello.jsp. This would generate following result:
4|Page
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:
<%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>
JSP Expression:
A JSP expression element contains a scripting language 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 tagged with HTML, in a JSP file. The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression. Following is the syntax of JSP Expression:
<jsp:expression> expression
5|Page
<html> <head><title>A Comment Test</title></head> <body> <p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> </body> </html>
This would generate following result: Today's date: 11-Sep-2010 21:24:25
JSP Comments:
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. Following is the syntax of 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>
This would generate following result:
A Test of Comments
There 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. Ignored by the JSP engine. An HTML comment. Ignored by the browser.
6|Page
JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. There is only one syntax for the Action element, as it conforms to the XML standard:
7|Page
response
config
8|Page
page
Exception
We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.
Control-Flow Statements:
JSP provides full power of Java to be embeded 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.
Decision-Making Statements:
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.
<%! 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>
This would produce following result: Today is not weekend Now look at the following switch...case 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;
9|Page
Loop Statements:
You can also use three basic types of looping blocks in Java: for, while,and do.while blocks in your JSP programming. 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>
This would produce following result:
JSP Tutorial
JSP Tutorial
JSP Tutorial
10 | P a g e
JSP Tutorial
JSP Tutorial
JSP Operators:
JSP supports all the logical and arithmatic operators supported by Java. Following table give a list of all the operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first. Category Postfix Unary Multiplicative Additive Shift Relational Equality Bitwise AND Bitwise XOR Bitwise OR () [] . (dot operator) ++ - - ! ~ */% +>> >>> << > >= < <= == != & ^ | Operator Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right
11 | P a g e
JSP Literals:
The JSP expression language defines the following literals:
Boolean: true and false Integer: as in Java Floating point: as in Java String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\. Null: null
You can download latest version of JavaMail (Version 1.2) from Java's standard website. You can download latest version of JavaBeans Activation Framework JAF (Version 1.0.2) from Java's standard website.
Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH.
<%@ page import="java.io.*,java.util.*,javax.mail.*"%> <%@ page import="javax.mail.internet.*,javax.activation.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %> <% String result; // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "mcmohd@gmail.com"; // Assuming you are sending email from localhost
12 | P a g e
13 | P a g e
type: This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy. Example Message.RecipientType.TO addresses: This is the array of email ID. You would need to use InternetAddress() method while specifying email IDs
<%@ page import="java.io.*,java.util.*,javax.mail.*"%> <%@ page import="javax.mail.internet.*,javax.activation.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %> <% String result; // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "mcmohd@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties object Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session mailSession = Session.getDefaultInstance(properties); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(mailSession); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Send the actual HTML message, as big as you like
14 | P a g e
<%@ page import="java.io.*,java.util.*,javax.mail.*"%> <%@ page import="javax.mail.internet.*,javax.activation.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %> <% String result; // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "mcmohd@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties object Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session mailSession = Session.getDefaultInstance(properties); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(mailSession);
15 | P a g e
16 | P a g e
Once you have all the information, you can use above mentioned programs to send email.
17 | P a g e
Learn Servlets Learn log4j Learn iBATIS Learn Java Learn JDBC Java Examples Learn Best Practices Learn Python Learn Ruby Learn Ruby on Rails Learn SQL Learn MySQL Learn AJAX Learn C Programming Learn C++ Programming Learn CGI with PERL Learn DLL Learn ebXML Learn Euphoria Learn GDB Debugger Learn Makefile Learn Parrot Learn Perl Script Learn PHP Script Learn Six Sigma Learn SEI CMMI Learn WiMAX Learn Telecom Billing
Learn ASP.Net Learn HTML Learn HTML5 Learn XHTML Learn CSS Learn HTTP Learn JavaScript Learn jQuery Learn Prototype Learn script.aculo.us Web Developer's Guide Learn RADIUS Learn RSS Learn SEO Techniques Learn SOAP Learn UDDI Learn Unix Sockets Learn Web Services Learn XML-RPC Learn UML Learn UNIX Learn WSDL Learn i-Mode Learn GPRS Learn GSM Learn WAP Learn WML Learn Wi-Fi
webmaster@TutorialsPoint.com
18 | P a g e