You are on page 1of 51

Introduction to

Server-Side Web Development


Introduction to Server-Side Web
Development
Server-Side Web Development with Servlets and
JSP; basic concepts and syntax
16
th
February 2006
Bogdan L. Vrusias
b.vrusias@surrey.ac.uk
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 2
Introduction
Most web sites want to display dynamic content based on
users requests and expectations.
Most contents, such as images, text, and banner ads, are
easiest to build with HTML editors.
We need to mix the "static" content of HTML files with
"directives" for accessing or generating dynamic content.

Introducing:
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 3
Contents
History of JavaServer Pages (JSP)
Fundamentals of server-side programming.
Comparison to other server-side languages
Fundamentals of JavaServer Pages / Servlets.
Servlets
JavaServer Pages
Tomcat
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 4
History: The Beginning
1991 beginning of WWW beginning of HTML
No dynamic pages the Webmaster
Too many static HTML pages had to be created for each
website.
Need for change
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 5
History: First approach - CGI
Solution Common Gateway Interface (CGI) technology
created.
Dynamic pagesusing Perl and C
Problem these languages are not the simplest
Need for change
Java had the answer Servlets
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 6
History: Servlets and JSP
Servlets are pure Java objects that generate HTML by writing it to a
stream.
The files do not contain any HTML tags; they simply contain Java
code which write out HTML (as strings) to produce the page that is
sent to the user's browser.
but it was quite painful to develop any large scale application with a
bunch of servlets running around doing println() statements.
This is why Sun invented JSPs in the first place: to compete with the
ease-of-development of Microsoft's ASP files, which could combine
HTML tags and code in a single file.
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 7
Definition
JSP provide server-side scripting support for generating
web pages with combined static and dynamic content.
JSP is a fast way to serve web pages that display
dynamically generated content.


Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 8
A dynamic Web Page
Static web page is a page whose content consists of some HTML that
was predetermined and was typed directly into a text editor and saved
as ".htm" or ".html" file.
Dynamic web page is a page whose content is generated at runtime
dynamically.
6. Browser processes HTML
and displays page.
2. Client request web page
1. Author writes
instructions
3. Web server
locates instructions
file
4. Web server
processes
instructions to
create HTML
5. HTML stream returned to browser
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 9
Requests and Responses
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 10
Other Server-Side programming languages
CGI
Perl, C, C++
ColdFusion
Tags with encapsulated functionality
ASP (Active Server Pages) and ASP .NET
VBasic, JavaScript, C#
ADO
PHP (Personal Home Pages)
Syntax similar to C and Perl
Open-source, cross-platform
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 11
JSP vs .NET and ASP
Similarities
Create interactive pages with web-based applications
Separates programming logic from page design through the use of
component technology
Faster and Easier alternative to older, more cryptic technologies
such as CGI
Differences (?)
JSP: Platform and server Independent
JSP can run on any web server
Supported by large number of tools
ASP: Relies on Microsoft platforms and servers
Restricted to MS Windows based platforms because of ActiveX
Controls (that is to change now?)
Can be ported to different platforms using third party products, but
ActiveX must be present on the platform.
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 12
Why Use JSPs?
Write once, run anywhere (JAVA).
JSPs are entirely platform independent, both in dynamic Web
pages and underlying server components.
Emphasize components.
JSPs encourage the use of reusable, cross-platform server
components called JavaBeans. Therefore saves development time,
while giving you the power and flexibility of the Java
programming language.
Provide a front door to the Enterprises Java platform.
JSPs are an integral part of the Java Platform for the Enterprise,
which brings Java technology to enterprise computing. You can
develop enterprise-wide or middle-tier server applications, using a
JSP web site as a front end.
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 13
Advantages of Java
According to java.sun.com:
More mature, powerful, and scalable than Basic-based scripting
languages
Java helps developers protect against system crashes, ASP and NT
systems are susceptible to crashing
Java helps with memory management by providing protection
against memory leaks
Well supported, large collection of APIs

Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 14
JSP Model Architectures
Model 1
Model 2
BROWSER
SERVLET
(CONTROLLER)
JSP
(VIEW)
JAVABEAN
request
response
JSP / Servlet Container
DATA DATA
Data Tier
BROWSER
JSP PAGE
JAVABEAN
request
response
JSP / Servlet Container
DATA DATA
Data Tier
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 15
JSP Model Architectures
Model 1
Simple and fast
Maintainability problems
Reusability Problems
Security Problems
Model 2 (also called Model-View-Controller)
Requires more initial effort and technical knowledge
Maintainability solutions vs. Model 1
Security solutions vs. Model 1
Reusability and extensibility solutions vs. Model 1
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 16
What are Servlets?
Servlets are objects that reside on a Java enabled web
server, that work on the request-response principle.
Servlets are to the server-side what applets are to the client
side
Servlets do not have a GUI associated with them
Servlets are faster and cleaner than CGI scripts
Servlets use a standard API
Servlets provide all the advantages of Java
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 17
Servlets Characteristics
Security
Servlets are called within the server context so they have all the security
of the server itself.
Theyre hidden from view and transmission.
Robustness
Rich application programming interfaces, APIs, are available making it
easier to build sophisticated applications (JDBC, EJB, etc.).
Performance
Servlets run in the same context as the application server and can be
preloaded or loaded on demand.
Theyre multi-threaded to scale with multiprocessors and heterogeneous
systems
Portability
Write-once, run-anywhere capability
They are able to exploit re-useable Java components called JavaBeans.
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 18
Servlet Code Sample
import javax.servlet.*;
import java.io.*;
import java.util.*;

public class SimpleServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
printWriter pw = response.getWriter();
pw.println("<html>\n<body>");
for(int counter = 1; counter <= 10; counter++) {
pw.println(counter + " Mississippi,<br>");
}
pw.println("<b>Ready or not, here I come!</b>");
pw.println("</body>\n<html>");
pw.close();
}
}
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 19
Servlet Lifecycle
1. When a server loads a servlet, it runs the servlet's init() method.
Even though most servlets are run in multi-threaded servers, there are
no concurrency issues during servlet initialization.
2. After the server loads and initializes the servlet, the servlet is able to
handle client requests. It processes them in its service() method.
3. Servlets run until they are removed from the service, by calling the
servlet's destroy() method.

NOTE: Servlets can run multiple service methods at a time. It is
important, therefore, that service methods be written in a thread-safe
manner. If, for some reason, a server should not run multiple service
methods concurrently, the servlet should implement the
SingleThreadModel interface.

Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 20
Servlet Lifecycle Diagram
Uninstantiated
Instantiated
Initialised
Servicing
Requests
Process
Requests
Process
Requests
Garbage
Collection
service()
destroy()
init()
doGet() doPost()
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 21
Servlet Architecture Overview
The central abstraction in the Servlet API is the Servlet interface.
All servlets implement this interface, either directly or, more
commonly, by extending a class that implements it such as
HttpServlet.
When a servlet accepts a call from a client, it receives two objects: one
is a ServletRequest and the other is a ServletResponse.
The ServletRequest class encapsulates the communication from the
client to the server
The ServletResponse class encapsulates the communication from the
servlet back to the client.
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 22
ServletRequest
The ServletRequest interface allows the servlet access to
information such as:
the names of the parameters passed in by the client
the protocol (scheme) being used by the client
the names of the remote host that made the request and the server that
received it.
It also provides the servlet with access to the input stream,
ServletInputStream, through which the servlet gets data from
clients that are using application protocols such as the http POST
method.
CLIENT SERVER
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 23
ServletResponse
The ServletResponse interface gives the servlet methods for
replying to the client. It allows the servlet to:
set the content length and mime type of the reply
provides an output stream, ServletOutputStream, and a "writer"
through which the servlet can send the reply data.
Subclasses of ServletResponse give the servlet more protocol-
specific capabilities. For example, HttpServletResponse
contains methods that allow the servlet to manipulate HTTP-specific
header information.
CLIENT SERVER
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 24
Interacting with Clients I
Servlet writers who are developing HTTP servlets that
specialize the HttpServlet class should override the
method or methods designed to handle the HTTP
interactions that their servlet will handle.
The candidate methods include:
doGet, for handling GET, conditional GET and HEAD requests
doPost, for handling POST requests
doPut, for handling PUT requests
doDelete, for handling DELETE requests

Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 25
Interacting with Clients II
An HttpServletRequest object provides access to HTTP header
data, such as any cookies found in the request and the HTTP method
with which the request was made. It allows the you to obtain the
arguments that the client sent as part of the request:
For any HTTP method, you can use the getParameter() or
getParameterValues() method, which will return the value(s) of a
named parameter. The method getParameterNames() provides the
names of the parameters.
For responding to the client, an HttpServletResponse object
provides ways of returning the response data to the user. You can use
the writer returned by the getWriter() method to return text data
to the user.
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 26
Reading Form Data Example - GET
<form action="/servlet/aservlet" method="get">
<input type="hidden" name="key1" value="abc"/>
<input type="hidden" name="key2" value="def"/>
<input type="submit" value="Go...."/>
</form>

When submitted, the browser would execute the following URL:
http://www.somewhere.com/servlet/aservlet?key1=x&
key2=y

Alternatively
<a href="/servlet/aservlet?key1=x&key2=y">
LINK</a>
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 27
Reading Form Data Example - POST
The HTML

...
<form action="/servlet/MyNameServlet" method="post">
<p>Please Enter your name</p>
<input type="text" name="yourname"/>
<input type="submit" value="Submit"/>
</form>
...




Example continues next page...
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 28
Reading Form Data Example - POST
The Servlet
...
public class AServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
String name=req.getParameter("yourname");
String reply="<HTML>\n"+
"<HEAD><TITLE>My Name Servlet Response</TITLE></HEAD>\n"+
"<BODY>\n<CENTER><BR><B>\n"+
"Hello "+name+"\n"+
"</B></CENTER>\n</BODY>\n</HTML>";
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println(reply);
out.close();
}
}
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 29
Demo

Some examples will now be demonstrated using the
NetBeans IDE running the Tomcat server

http://host/servlet/ServletName
http://host/servlet/PackageName.ServletName

or otherwise if servlet is declared within the web.xml

http://host/ServletName
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 30
How Servlets relate to JSPs
JSPs and servlets are two different ways to accomplish the
same goal: generating dynamic HTML pages using Java
code. One puts Java code in your HTML, and one puts
HTML in your Java code.
Functionally, they are equivalent. In fact, under the covers,
the web server takes a JSP and converts it to the
corresponding servlet and dynamically compiles it.

BUT servlets have the following deficiencies:
It is hard to write and maintain the HTML
You cannot use standard HTML tools
The HTML is inaccessible to non-Java developers
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 31
JSP Code Sample
<%@ page language="java" %>

<html>
<body>

<% for (int counter = 1; counter <= 10; counter++) {%>
<%= counter %> Mississippi,<BR>
<% }%>

<b>Ready or not, here I come!</b>

</body>
</html>

Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 32
JSP Syntax
Scriptlets
Expressions
Declarations
Comments
Directives
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 33
Scriptlets
<%
// Java Code
%>

e.g.
<% for (int i = 1; i <= 10; i++) {%>
<%= i %> Mississippi,<BR>
<% }%>
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 34
Expressions
An expression prints out a string value on the page's buffer
output:
<%= counter %>
<%= new java.util.Date() %>

Using scriplets this would look like:
<% out.print(counter) %>
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 35
Declarations
<%!

// this integer can be used anywhere in this JSP page
private int myVariable = -1;

// this function can be called from anywhere in this JSP page
public boolean isPositive() {
return ( myVariable > 0 );
}

%>
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 36
Comments
The comments are not printed on page's buffer, therefore are not viewed by the
client.
<%--
comments over many
lines of code
--%>

Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 37
Directives
Here is what directives look like in a general form:
<%@ directive attribute="someValue"
attribute="anotherValue" ... %>

There are three directives:
<%@ page ... %> specifies information that affects the page
e.g. <%@ page import="java.util.Date, java.text.*" %>

<%@ include ... %> includes a file at the location of the include directive
(parsed)
e.g. <%@ include file="/copyright.html" %>

<%@ taglib ... %> allows the use of custom tags in the page
e.g. <%@ taglib uri="/WEB-INF/tlds/myTagLib.tld"
prefix="myPrefix" %>
<myPrefix:displayImage file="logo.jpg" />
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 38
Page Directive
<%@ page import="package.class" %>

<%@ page errorPage="Relative URL" %>
<%@ page isErrorPage="true" %>

<%@ page contentType="application/vnd.ms-excel"
%>


Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 39
Include Directive
Use the include directive to include a file in the main JSP
document at the time the document is translated into a
servlet.
What is included is the actual content of the respective file.

<%@ include file="header.jsp" %>
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 40
JSP Action Elements
There are three different types of action elements:
Standard
<jsp:include>
<jsp:forward>
<jsp:useBean>
<jsp:plugin>
<jsp:getProperty> and <jsp:setProperty>
JSTL (JavaServer Pages Standard Tag Library)
It provides tag libraries in the subject of Internationalization and
formatting, XML, SQL, and the core tags.
Custom
Tags constructed by the developer.
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 41
Include Action Element
The jsp:include action lets you include the output (not the actual code)
of a page at request time:

<jsp:include page="header.jsp" />

<jsp:include page="header.jsp" %>
<jsp:param name="title" value="Welcome"/>
</jsp:include>

NOTE: Is it similar to <%@ include file="header.jsp"%> ???
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 42
Forward Action Element
The jsp:forward action lets you forward the output to another page:

<jsp:forward page="main.jsp" />

NOTE: Not recommended !!! Better use the forward method of the
RequestDispatcher object.
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 43
Implicit Objects and the JSP Environment
The scriptlets and expressions written in a JSP page do not stand alone
as a complete program they need an environment in which to
operate.
The JSP container provides this environment and makes it accessible
to the page author through what are called implicit objects:
request (HttpServletRequest)
response (HttpServletResponce)
application (ServletContext)
session (HttpSession)
out (JspWriter)
pageContext
config
page
exception
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 44
Basic request Methods
String getParameter(String name)
Enumeration getParameterNames()
String getMethod() (e.g "POST", "GET")
Cookie[] getCookies()
String getHeader(String name)
Enumeration getHeaderNames()
HttpSession getSession(boolean create)
...
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 45
Basic response Methods
void sendRedirect()
void addCookie(Cookie cookie)
void setHeader(String name)
void addHeader(String name)
void sendError(int sc [, String msg])

Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 46
Basic session Methods
Object getAttribute(String name)
void setAttribute(String name, Object value)
Enumeration getAttributeNames()
int setMaxInactiveInterval()
int getMaxInactiveInterval()
void invalidate()
void isNew()
void logout()
String getId()
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 47
Basic application Methods
String getRealPath(String path)
Object getAttribute(String name)
void setAttribute(String name , Object value)
void removeAttribute(String name)
Enumeration getAttributeNames()
void log(String msg)
URL getResource(String path)
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 48
Basic out Methods
void print(String value)
void println(String value)
void newLine()
void clear()
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 49
Tomcat
Tomcat is the official JavaServer Pages Web server.
Tomcat is the official reference implementation of the Java
Servlet and JavaServer Pages technologies. Developed
under the Apache license in an open and participatory
environment.
Other popular Web servers are:
Apache
Java Application Server
Macromedia JRun
Jetty
Internet Information Server (IIS)
Jigsaw
http://jakarta.apache.org/tomcat/
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 50
Exploring the NetBeans IDE and Tomcat
http://www.netbeans.org
Please follow the demonstration
Introduction to
Server-Side Web Development
16
th
February 2006 Bogdan L. Vrusias 2006 51
Closing

Questions???
Remarks???
Comments!!!
Evaluation!

You might also like