This slide is about basics of java servlet and java server page.
A basic example of JSP using multiple directives.
Further information of setting up and using of Apache Tomcat server.
2. What is JSP?
• Java Server Pages (JSP) is a technology for developing
web pages.
• It supports dynamic content which helps developers
to insert java code in HTML pages
• It uses of special JSP tags, most of which start with
<% and end with %>.
• A Java Server Pages component is a type of Java
servlet that is designed to fulfil the role of a user
interface for a Java web application.
2
3. Why Use JSP?
• JSP offer several advantages in comparison
with the CGI(Common Gateway Interface).
– 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.
3
4. Why Use JSP? contd..
– Java Server 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.
4
5. Advantages of JSP
• Following is the list of other advantages of
using JSP over other technologies:
– vs. Active Server Pages (ASP):
• dynamic part is written in Java, not Visual Basic or other
MS specific language,
• it is portable to other operating systems and non-
Microsoft Web servers.
– vs. Pure Servlets:
• It is more convenient to write (and to modify) regular
HTML
5
6. Advantages of JSP contd..
– vs. JavaScript:
• JavaScript can generate HTML dynamically on the client
but can hardly interact with the web server to perform
complex tasks.
– vs. Static HTML:
• Regular HTML, of course, cannot contain dynamic
information.
6
8. JSP Architecture contd..
8
• JSP Processing:
1. Browser sends an HTTP request to the web
server.
2. The web server recognizes that the HTTP request
is for a JSP page (.jsp page) and forwards it to a
JSP engine.
9. JSP Architecture contd..
3. The JSP engine loads the JSP page from disk
and converts it into a servlet content. 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.
4. The JSP engine compiles the servlet into an
executable class and forwards the original request
to a servlet engine.
9
10. JSP Architecture contd..
5. Servlet engine loads the Servlet class and executes
it. & produces an output in HTML format, which
the servlet engine passes to the web server inside
an HTTP response.
6. The web server forwards the HTTP response to
your browser in terms of static HTML content.
10
12. JSP and Servlets
• Each JSP page is turned into a Java servlet,
compiled and loaded. This compilation
happens on the first request. After the first
request, the file doesn't take long to load
anymore.
• Every time you change the JSP file, it will be
re-compiled again.
12
13. Generated servlets
13
• You can examine the source code produced by
the JSP translation process.
• There is a directory called generated in Sun
Java J2EE Application Server where we can
find the source code.
• Note that the _jspService method corresponds
to the servlet service method.
(which is called by doGet or doPost)
14. JSP elements (overview)
14
• Directives of the form <%@ . . . %>
• Scripting elements
– Expressions of the form <%= expr %>
– Scriptlets of the form <% code %>
– Declarations of the form <%! code %>
– JSP Comments <%-- . . . --%>
• Standard actions
– Example: <jsp:useBean> …. </jsp:useBean>
• Implicit variables like request, response, out
15. JSP Directives
• They have the form
<%@ name attribute1= “ . . .”, attribute2=“. . . ”...%>
15
page
include
taglib
Specify page properties
Include a file at translation time
Specify custom tags
16. JSP Directive Examples
• Import java packages
– <%@ page import=“ java.util .*, java.sql .* ” %>
• „Multiple import statements
– <%@ page import=“ java.util .* ” %>
– <%@ page import=“ java.sql .* ” %>
• Including file at translation time
– <%@ include file=“ header.html ” %>
• For include the path is relative to the JSP file
16
17. JSP Scripting Elements: Expressions
• For an expression scripting element like
<%= expr %>, expr is evaluated and the
result is converted to a string and placed into
the JSP's servlet output stream. In a Java
servlet this would be equivalent to
PrintWriter out = response.getWriter();
. . .
out.print(expr);
17
18. JSP Expression Examples
• Displaying request parameters (request is an
implicit object available in a JSP)
– Your name is <%= request.getParameter(“name”) %>
– and your age is <%= request.getParameter(“age”) %>
• Doing calculations
The value of pi is <%= Math.PI %> and the square root of
two is <%= Math.sqrt(2.0) %> and today's date is <%= new
java.util.Date() %> .
18
19. JSP Scripting Elements: Scriptlet
• For a scriplet <%= statements %> the Java
statements are placed in the translated
servlet's _jspService method body (which is
called by either doGet or doPost)
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException, ServletException
{
...
statements
...
} 19
20. JSP Scriplet Examples
• Check a request parameter
<% String name = request.getParameter("name");
if (name == null)
{ %>
<h3>Please supply a name</h3>
<% }
else
{ %>
<h3>Hello <%= name %></h3>
<% } %>
In this example, there are 3 scriptlets elements and one
expression element 20
21. JSP Scripting Elements: Declaration
• For a declaration <%! declarations
%> the Java statements are placed in the
class outside the _jspService method.
• Declarations can be Java instance
variable declarations or Java methods
// declarations would go here
public void _jspService(...)
{
...
} 21
22. JSP Declaration examples
• Declaring instance variables
<%! private int count = 0; %>
...
The count is <%= count++ %> .
• Declaring methods
<%!
private int toInt(String s)
{
return Integer.parseInt(s);
}
%> 22
23. Including Files
• Including files at translation time (when
JSP is translated to a servlet)
<%@ include file="filename" %>
• Including files at request time
<jsp:include page="filename" flush = "true" />
23
24. A simple JSP
<html>
<head><title>JSP Test</title></head>
<body>
<h1>JSP Test</h1>
Time: <%= new java.util.Date() %>
</body>
</html>
24
The expression scripting
element <%= ... %> is
equivalent to the scriptlet
<% out.print(...); %>
25. The Implicit out Object
• In a scriptlet <% ... %> you can use the
out object to write to the output stream.
Example:
<%
out.print ("The sum is “);
out.print("1 + 2 = " + (1+2));
%>
25
26. The Implicit request Object
• In a scriptlet <% ... %> you can use the request
object to access GET/POST parameters.
• Example:
<html>
<head><title>...</title></head>
<body>
<h1>...</h1>
<p><%= request.getParameter("greeting") %></p>
</body></html>
26
35. Standard action elements
Action element Description
<jsp:useBean> Makes a JavaBeans component available in a page
<jsp:getProperty>
Gets a property value from a JavaBeans component and adds it to
the response
<jsp:setProperty> Set a JavaBeans property value
<jsp:include>
Includes the response from a servlet or JSP page during the request
processing phase
<jsp:forward> Forwards the processing of a request to a servlet or JSP page
<jsp:param>
Adds a parameter value to a request handed off to another servlet
or JSP page using <jsp:include> or <jsp:forward>
36. Standard action elements
Action element Description
<jsp:plugin>
Generates HTML that contains the appropriate browser-dependent
elements (OBJECT or EMBED) needed to execute an applet with the
Java Plugin software
<jsp:attribute> Sets the value of an action attribute based on the body of this element
<jsp:body>
Sets the action element body based on the body of this element.
Required when the action element body contains <jsp:attribute>
action elements
<jsp:element>
Dynamically generates an XML element, optionally with attributes
and a body defined by nested <jsp:attribute> and <jsp:body>
actions
<jsp:text>
Used to encapsulate template text that should be used verbatim;
typically only needed in JSP pages written as XML documents
37. • Scope
– Implicit objects provide access to server side objects
• e.g. request, response, session etc.
– There are four scopes of the objects
• Page: Objects can only be accessed in the page where they are
referenced
• Request: Objects can be accessed within all pages that serve the
current request.
(Including the pages that are forwarded to and included in the
original jsp page)
• Session: Objects can be accessed within the JSP pages for which
the objects are defined
• Application: Objects can be accessed by all JSP pages in a given
context
Java Implicit Objects
38. • request: Reference to the current request
• response: Response to the request
• session: session associated woth current request
• application: Servlet context to which a page belongs
• pageContext: Object to access request, response,
session and application associated with a page
• config: Servlet configuration for the page
• out: Object that writes to the response output stream
• page: instance of the page implementation class (this)
• exception: Available with JSP pages which are error
pages
Java Implicit Objects
List
39. <html>
<head>
<title>Implicit Objects</title>
</head>
<body style="font-family:verdana;font-size:10pt">
<p>
Using Request parameters...<br>
<b>Name:</b> <%= request.getParameter("name") %>
</p>
<p>
<% out.println("This is printed using the out implicit
variable"); %>
</p>
<p>
Storing a string to the session...<br>
<% session.setAttribute("name", "Meeraj"); %>
Retrieving the string from session...<br>
<b>Name:</b> <%= session.getAttribute("name") %>
</p>
Java Implicit Objects
Example
<p>
Storing a string to the application...<br>
<% application.setAttribute("name", "Meeraj"); %>
Retrieving the string from application...<br>
<b>Name:</b>
<%= application.getAttribute("name") %>
</p>
<p>
Storing a string to the page context...<br>
<% pageContext.setAttribute("name", "Meeraj"); %>
Retrieving the string from page context...</br>
<b>Name:</b>
<%= pageContext.getAttribute("name") %>
</p>
</body>
</html>
40. • Save file:
– $TOMCAT_HOME/webapps/jsp/Implicit.jsp
• Access file
– http://localhost:8080/jsp/Implicit.jsp?name=Sanjay
• Results of the execution
Using Request parameters...
Name: sanjay
This is printed using the out implicit variable
Storing a string to the session...
Retrieving the string from session...
Name: Meeraj
Storing a string to the application...
Retrieving the string from application...
Name: Meeraj
Storing a string to the page context...
Retrieving the string from page context...
Name: Meeraj
Example Implicit Objects
Deploy & Run
42. What is Tomcat?
• Tomcat is a Servlet container (Web server that
interacts with Servlets) developed under the Jakarta
Project of Apache Software Foundation
• Tomcat implements the Servlet and the Java Server
Pages (JSP) specifications of Sun Microsystems
• Tomcat is an open-source, non commercial project
– Licensed under the Apache Software License
• Tomcat is written in Java (OS independent)
43. A Servlet Example
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html><head><title>Hello</title></head>");
out.println("<body>");
out.println("<h2>" + new java.util.Date() + "</h2>");
out.println("<h1>Hello World</h1></body></html>");
}
} HelloWorld.java
http://localhost/dbi/hello
44. A JSP Example
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2><%= new java.util.Date() %></h2>
<h1>Hello World</h1>
</body>
</html> hello.jsp
http://localhost/dbi/hello.jsp
47. Tomcat Directory Structure
Tomcat-Home
bin common
Tomcat-Base
webapps work
lib classesROOT myApp1 myApp2server.xml
WEB-INF
lib classesweb.xml
server sharedlogsconf
lib classes
48. Base and Home Directories
• The directory TOMCAT-HOME contains
executables and libraries required for the server
launching, running and stopping
– This directory is placed under /usr/local/…
• The directory TOMCAT-BASE contains the
Web-site content, Web applications and
configuration data
– This directory is placed under your home directory
49. Installing Tomcat
• Create a directory for tomcat base
– For example: mkdir ~/tomcat-base
• Set the environment variable CATALINA_BASE to
your tomcat-base directory
– For example: setenv CATALINA_BASE ~/tomcat-base
– Insert this line into your .cshrc file
• Run ~dbi/tomcat/bin/setup
• $CATALINA_BASE is now a regular Tomcat base
directory, and Tomcat is ready to run
50. Running Tomcat
• To start tomcat use ~dbi/tomcat/bin/catalina run
• Or, in background, ~dbi/tomcat/bin/catalina start
• To stop tomcat use ~dbi/tomcat/bin/catalina stop
• To see the default page of Tomcat from your browser
use the URL http://<machine-name>:<port>/
– machine-name is the name of the machine on which Tomcat
runs and port is the port you chose for Tomcat
• You can also use http://localhost:<port>/ if your
browser runs on the same machine as Tomcat
53. Choosing a port for Tomcat
• In the file $CATALINA_HOME/conf/server.xml you
will find the element Connector of Service
“Catalina”
• Choose a port (greater than 1024) and change the
value of the port attribute to your chosen one:
<Server>
…
<Service name="Catalina”>
<Connector port="8090"/>
…
</Service>
…
</Server>
55. Creating Web Applications
• A Web application is a self-contained subtree of
the Web site
• A Web application usually contains several Web
resources like HTML files, Servlets, JSP files, and
other resources like Database tables
• Each Web application has its own subdirectory
under the directory
$CATALINA_BASE/webapps/
56. The Directory Structure of a Web Application
• Tomcat automatically identifies a directory
$CATALINA_BASE/webapps/myApp/ with
the relative URL /myApp/
• For example, a file named index.html in myApp
is mapped to by the following URLs:
http://machine:port/myApp/index.html
http://machine:port/myApp/
57. The Directory Structure of a Web Application
• You can also use subdirectories under myApp
• For example: the file myApp/myImages/im.gif is
mapped to by the URL
http://machine:port/myApp/myImages/im.gif
• By default, Tomcat maps the root directory
(http://localhost:8090/) to the directory
webapps/ROOT/
– You can change this default
58. The Directory Structure of a Web
Application
• An application's directory must contain
the following:
–The directory WEB-INF/
–A legal web.xml file under WEB-INF/
myApp
WEB-INF
web.xml
<web-app>
</web-app>
61. Configuring a Web Application
• Application-specific configuration and declarations are
written in the file myApp/WEB-INF/web.xml
• This file contains:
– Servlet declarations, mappings and parameters
– Default files for directory requests
– Error pages (sent in cases of HTTP errors)
– Security constraints
– Session time-out specification
– Context (application) parameters
– And more…
62. Error Pages
• Use the error-page element to define the
page sent in case of an HTTP error that occurs
within the application context
• An error page element has two sub elements:
–error-code - the HTTP error status code
–location - the page that should be sent
63. Welcome Page Example
<html>
<head><title>Not Found</title></head>
<body>
<h1 style="text-align:center; color:green">
Sorry, no such file...
</h1>
</body>
</html>
my404.html
<web-app>
<error-page>
<error-code>404</error-code>
<location>/my404.html</location>
</error-page>
</web-app>
web.xml
64.
65.
66. Welcome Pages
• The (optional) welcome-file-list element contains a list
of file names
• When the URL request is a directory name, Tomcat
automatically brings the first file on the list
• If that file is not found, the server then tries the next
file in the list, and so on
• This file can be of any type, e.g., HTML, JSP, image, etc.
• The default welcome list for all applications is set in
$CATALINA_BASE/conf/web.xml
69. Tomcat and Java Classes
• Tomcat uses Java classes you provide in order
to run Servlets and JSP files
– For example, the Servlets themselves!
• Tomcat 5.x initialization scripts ignore your
environment CLASSPATH variable
• Classes are expected to be placed (or linked)
at some predefined places in its directories
70. Java Class Locations
• Tomcat expects to find Java classes in class files (in a
directory named classes) and JAR files (in a
directory named lib) in the following places:
• TOMCAT-HOME/common/
– Basic runtime classes. No need to touch this directory
• $CATALINA_BASE/shared/
– Classes that are used by all the Web applications
• $CATALINA_BASE/webapps/myApp/WEB-INF/
– Application-specific classes (Servlets are typically
here)
71. Java Class Locations
Tomcat-Home
bin common
Tomcat-Base
webapps work
lib classesROOT myApp1 myApp2server.xml
WEB-INF
lib classesweb.xml
server sharedlogsconf
lib classes
75. Web Archives
• A WAR (Web ARchive) file is a JAR file that contains a
whole Web-application directory
• For example, to create a WAR file of myApp do:
jar cvf myApp.war webapps/myApp/*
• Tomcat unpacks all WAR files found in
$CATALINE_BASE/webapps/ at statup
– The unpacked directory and context will be named as the
WAR file name (without the .war extension)
– The WAR will not be unpacked if webapps/ already contains
the directory and the WAR is not newer...
76. Reflecting Application Changes
• Changes in your Java classes may not be reflected
in your application
– Old versions may already have been loaded
– The application needs to be reloaded
• Changes in other files like HTML or JSP are always
reflected
• Modification of web.xml automatically causes
the application to be reloaded
77. Tomcat Manager
• Tomcat 5.0 comes with a Web application
called “manager”, which supports functions
for managing Web applications
• You can either use the HTML interface at
http://<machine>:<port>/manager/html/ or
send direct HTTP requests to it
• You will need to authenticate as a privileged
user
– Use the username “admin” with no password
78. Tomcat Manager
• Using the manager, you can
– Deploy a Web application by posting a WAR file
– Undeploy a deployed Web application
– Start/stop a Web application (make it
available/unavailable)
– Reload an existing Web application (unpack new WARs)
• Warning: while “stop” makes an application unavailable,
“undeploy” deletes the application directory and WAR file
from webapps/