You are on page 1of 64

Servlets

15-Dec-12

Servers

A server is a computer that responds to requests from a client

Typical requests: provide a web page, upload or download a file, send email

A server is also the software that responds to these requests; a client could be the browser or other software making these requests Typically, your little computer is the client, and someone elses big computer is the server

However, any computer can be a server It is not unusual to have server software and client software running on the same computer

Apache

Apache is a very popular server

66% of the web sites on the Internet use Apache Full-featured and extensible Efficient Robust Secure (at least, more secure than other servers) Up to date with current standards Open source Free

Apache is:

Why use anything else?


3

Ports

A port is a connection between a server and a client

Ports are identified by positive integers A port is a software notion, not a hardware notion, so there may be very many of them Typical port numbers:

A service is associated with a specific port

21FTP, File Transfer Protocol 22SSH, Secure Shell 25SMTP, Simple Mail Transfer Protocol 53DNS, Domain Name Service 80HTTP, Hypertext Transfer Protocol 8080HTTP (used for testing HTTP) 7648, 7649CU-SeeMe 27960Quake III

These are the ports of most interest to us

Ports II

My UPenn Web page is:


http://www.cis.upenn.edu/~matuszek

But it is also:
http://www.cis.upenn.edu:80/~matuszek

The http: at the beginning signifies a particular protocol (communication language), the Hypertext Transfer Protocol The :80 specifies a port By default, the Web server listens to port 80

The Web server could listen to any port it chose This could lead to problems if the port was in use by some other server For testing servlets, we typically have the server listen to port 8080 If I had sent it to some other port, say, 99, my request would either go unheard, or would (probably) not be understood
5

In the second URL above, I explicitly sent my request to port 80

CGI Scripts

CGI stands for Common Gateway Interface


Client sends a request to server Server starts a CGI script client

server
script

Script computes a result for server and quits


Server returns response to client Another client sends a request

client

Server starts the CGI script again


Etc.

Servlets

A servlet is like an applet, but on the server side


Client sends a request to server Server starts a servlet client

server
servlet

Servlet computes a result for server and does not quit


Server returns response to client Another client sends a request

client

Server calls the servlet again


Etc.

What are Java Servlets


An alternate form of server-side computation that uses Java The Web server is extended to support an API, and then Java programs use the API to create dynamic web pages Using Java servlets provides a platform-independent replacement for CGI scripts. Servlets can be embedded in many different servers because the servlet API, which you use to write servlets, assumes nothing about the server's environment or protocol.

Servlets vs. CGI scripts

Advantages:

Running a servlet doesnt require creating a separate process each time A servlet stays in memory, so it doesnt have to be reloaded each time There is only one instance handling multiple requests, not a separate instance for every request Untrusted servlets can be run in a sandbox Less choice of languages (CGI scripts can be in any language)

Disadvantage:

Tomcat

Tomcat is the Servlet Engine than handles servlet requests for Apache

Tomcat is a helper application for Apache Its best to think of Tomcat as a servlet container Apache can be installed without Tomcat Tomcat can be installed without Apache

Apache can handle many types of web services


Its easier to install Tomcat standalone than as part of Apache

By itself, Tomcat can handle web pages, servlets, and JSP

Apache and Tomcat are open source (and therefore free)

10

Servlets

A servlet is any class that implements the javax.servlet.Servlet interface

In practice, most servlets extend the javax.servlet.http.HttpServlet class Some servlets extend javax.servlet.GenericServlet instead

Servlets, like applets, usually lack a main method, but must implement or override certain other methods

11

The Advantages of Servlets Over Traditional CGI

Efficiency

CGI invoking

Overhead of starting a new process can dominate the execution time. For N simultaneous request, the same code is loaded into memory N times. When terminated, lose cache computation, DB connection & .. JVM stays running and handles each request using Java thread. Only a single copy is loaded into memory Straightforward to store data between requests

Servlet

The Advantages of Servlets Over Traditional CGI

Convinient

CGI invoking

Easy to install and setup Provides an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions and other utilities. No need to learn new programming languages if you are familiar with Java already. Easy to implement DB connection pooling & resource-sharing optimization.

Servlet

Servlet Life Cycle

Initialization

the servlet engine loads the servlets *.class file in the JVM memory space and initializes any objects when a servlet request is made,

Execution

a ServletRequest object is sent with all information about the request a ServletResponse object is used to return the response

Destruction

the servlet cleans up allocated resources and shuts down

Important servlet methods, I

When a servlet is first started up, its init(ServletConfig config) method is called

init should perform any necessary initializations init is called only once, and does not need to be thread-safe

Every servlet request results in a call to service(ServletRequest request, ServletResponse response)


service calls another method depending on the type of service requested Usually you would override the called methods of interest, not service itself service handles multiple simultaneous requests, so it and the methods it calls must be thread safe
destroy is called only once, but must be thread safe (because other threads may still be running)
15

When the servlet is shut down, destroy() is called

Client Interaction

When a servlet accepts a call from a client, it receives two objects:

A ServletRequest, which encapsulates the communication from the client to the server. A ServletResponse, which encapsulates the communication from the servlet back to the client.

ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

The ServletRequest Interface

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, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream. Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

Interfaces that extend ServletRequest interface allow the servlet to retrieve more protocol-specific data. For example, the HttpServletRequest interface contains methods for accessing HTTP-specific header information.

The ServletResponse Interface

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.

Interfaces that extend the ServletResponse interface give the servlet more protocol-specific capabilities.

For example, the HttpServletResponse interface contains methods that allow the servlet to manipulate HTTP-specific header information.

HTTP requests

When a request is submitted from a Web page, it is almost always a GET or a POST request The HTTP <form> tag has an attribute action, whose value can be "get" or "post" The "get" action results in the form information being put after a ? in the URL

Example: http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF8&q=servlets The & separates the various parameters Only a limited amount of information can be sent this way

"put" can send large amounts of information


19

Important servlet methods, II

The service method dispatches the following kinds of requests: DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE

A GET request is dispatched to the doGet(HttpServletRequest request, HttpServletResponse response) method A POST request is dispatched to the doPost(HttpServletRequest request, HttpServletResponse response) method These are the two methods you will usually override doGet and doPost typically do the same thing, so usually you do the real work in one, and have the other just call it public void doGet(HttpServletRequest request, HttpServletResponse response) { doPost(request, response); }

20

A Hello World servlet


(from the Tomcat installation documentation)

public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>Hello World</H1>\n" + "</BODY></HTML>"); } Dont worry, well take this a little at a time! }
21

The superclass

public class HelloServlet extends HttpServlet {

Every class must extend GenericServlet or a subclass of GenericServlet

GenericServlet is protocol independent, so you could write a servlet to process any protocol In practice, you almost always want to respond to an HTTP request, so you extend HttpServlet

A subclass of HttpServlet must override at least one method, usually one doGet, doPost, doPut, doDelete, init and destroy, or getServletInfo
22

The doGet method

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { This method services a GET request The method uses request to get the information that was sent to it The method does not return a value; instead, it uses response to get an I/O stream, and outputs its response Since the method does I/O, it can throw an IOException Any other type of exception should be encapsulated as a ServletException The doPost method works exactly the same way

23

Parameters to doGet

Input is from the HttpServletRequest parameter

Our first example doesnt get any input, so well discuss this a bit later

Output is via the HttpServletResponse object, which we have named response

I/O in Java is very flexible but also quite complex, so this object acts as an assistant

24

Using the HttpServletResponse

The second parameter to doGet (or doPost) is HttpServletResponse response Everything sent via the Web has a MIME type The first thing we must do with response is set the MIME type of our reply: response.setContentType("text/html");

This tells the client to interpret the page as HTML

Because we will be outputting character data, we need a PrintWriter, handily provided for us by the getWriter method of response: PrintWriter out = response.getWriter(); Now were ready to create the actual page to be returned

25

Input to a servlet

A GET request supplies parameters in the form

URL ? name=value & name=value & name=value (Illegal spaces added to make it more legible) Actual spaces in the parameter values are encoded by + signs Other special characters are encoded in hex; for example, an ampersand is represented by %26

Parameter names can occur more than once, with different values A POST request supplies parameters in the same syntax, only it is in the body section of the request and is therefore harder for the user to see

26

Getting the parameters

Input parameters are retrieved via messages to the HttpServletRequest object request

Most of the interesting methods are inherited from the superinterface ServletRequest
Returns an Enumeration of the parameter names If no parameters, returns an empty Enumeration Returns the value of the parameter name as a String If the parameter doesnt exist, returns null If name has multiple values, only the first is returned Returns an array of values of the parameter name If the parameter doesnt exist, returns null
27

public Enumeration getParameterNames()


public String getParameter(String name)


public String[] getParameterValues(name)


Additional Capabilities of HTTP Servlets

Cookies are a mechanism that a servlet uses to have clients hold a small amount of state-information associated with the user. Servlets can use the information in a cookie as the user enters a site (as a low-security user sign-on,for example), as the user navigates around a site (as a repository of user preferences for example), or both. HTTP servlets also have objects that provide cookies. The servlet writer uses the cookie API to save data with the client and to retrieve this data.

Sessions Source Code 1/2


import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*;

public class SessionExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); // print session info Date created = new Date( session.getCreationTime()); Date accessed = new Date(session.getLastAccessedTime());

What is JSP?

A Java Servlet is a Java program that is run on the server

There are Java classes for retrieving HTTP requests and returning HTTP responses

A Java Servlet must return an entire HTML page, so all tuning of the page must be done in a Java program that needs to be re-compiled Java Server Pages (JSP)

use HTML and XML tags to design the page and JSP scriplet tags to generate dynamic content (Easier for separation between designer & developer) use Java Beans and useful built-in objects for more convinience

JSP Life Cycle


JSP page (MyFirstJSP.jsp) -> Translated to Servle (MyFirstJSP.servlet) -> Compiled to class (MyFirstJSP.class) -> Loaded into memory (Initialization) -> Execution (repeats) -> Destruction Any change in JSP page automatically repeats the whole life cycle.

Introduction

A Java Servlet is a Java program that is run on the server

There are Java classes for retrieving HTTP requests and returning HTTP responses

A Java Servlet must return an entire HTML page, so all tuning of the page must be done in a Java program that needs to be re-compiled On the other hand Java Server Pages (JSP)

use HTML and XML tags to design the page and JSP scriplet tags to generate dynamic content use Java Beans, which are reusable components that are invoked by scriplets

How to Use JSPs with a Form

Start writing a jsp source file, creating an html form and giving each form element a name Write the Bean in a .java file, defining properties, get and set methods corresponding to the form element names Return to the jsp source file, add a <jsp:useBean> tag to locate an instance Add a <jsp:setProperty> tag to set properties in the Bean from the html form Add a <jsp:getProperty> tag to retrieve the data from the Bean If more processing is required, use the request object from within a scriplet

What do JSPs contain?

Template data

Everything other than elements (eg. Html tags) based on XML syntax

Elements

<somejsptag attribute name=atrribute value> BODY </somejsptag>

Directives Scripting

Declarations Scriptles Expressions

Standard Actions

Directives

<%@ directivename attribute=value attribute=value %> The page directive


<%@ page ATTRIBUTES %> language, import, Buffer, errorPage, <%@ page languange=java import=java.rmi.*,java.util.* %>

The include directive


<%@ include file=Filename %> the static file name to include (included at translation time)
<% taglib uri=taglibraryURI prefix=tagPrefix %>

The taglib directive

Scripting (Declaration, Expressions, Scriptlets)

<%! . . %> declares variables or methods


define class-wide variables <%! int i = 0; %> <%! int a, b; double c: %> <%! Circle a = new Circle(2.0); %> You must declare a variable or method in a jsp page before you use it The scope of a declaration is the jsp file, extending to all includes

<%= . . %> defines an expression and casts the result as a string

Scripting II

<%= . . %> can contain any language expression, but without a semicolon, e.g. <%= Math.sqrt(2) %> <%= items[I] %> <%= a + b + c %> <%= new java.util.Date() %> <% . . %> can handle declarations (page scope), expressions, or any other type of code fragment <% for(int I = 0; I < 10; I++) { out.println(<B> Hello World: + I); } %>

Standard Actions

<jsp:useBean> : associates an instance of a java object with a newly declard scripting variable of the same id

<jsp:useBean id=name scope=page|request|session|application class=className /> <jsp:setProperty name=beanid property=* />

<jsp:setProperty>

<jsp:getProperty> :action places the value of a Bean instance property, converted to a string, into the implicit out object

<jsp:getProperty name=beanid property=propertyName />

<jsp:param>

<jsp:param name=paramname value=paramvalue />

<jsp:include> :Include static or dynamic (jsp) pages with optional parameters to pass to the included page.

<jsp:include page=filename /> <jsp:include page=urlSpec> <jsp:param name paramname value=value> </jsp:include>

<jsp:forward> : allows the runtime dispatch of the current request to a static resource, jsp pages or java servlet in the same context as the current page.

<jsp:forward page=url /> <jsp:include page=urlSpec> <jsp:param name paramname value=value> </jsp:forward>

JSP and Scope


Page - objects with page scope are accessible only within the page where they are created Request - objects with request scope are accessible from pages processing the same request where they were created Session - ojbects with session scope are accessible from pages processing requests that are in the same session as the one in which they were created Application - objects with application scope are accessible from pages processing requests that are in the same application as the one in which they were created All the different scopes behave as a single name space

Implicit Objects

These objects do not need to be declared or instantiated by the JSP author, but are provided by the container (jsp engine) in the implementation class request Object (javax.servlet.ServletRequest) response Object (javax.servlet.ServletResponse) session Object (javax.servlet.http.HttpSession) application Object out Object config Object page Object pageContext Object (javax.servlet.jsp.PageContext) exception

Hellouser.jsp
<%@ page import=hello.NameHandler %> <jsp:useBean id=mybean scope=page class=hello.NameHandler /> <jsp:setProperty name=myBean property=* /> <html><head><title>hello user</title></head> <body> <h1>My name is Duke. Whats yours?</h1> <form method=get> <input type=text name=username><br> <input type=submit value=submit> </form> <% if ( request.getParameter(username) != null) { %><%@ include file=response.jsp %> <% } %></body>

Namehandler.java
package hello public class NameHandler { private String username; public NameHandler() { username = null; } public void setUsername ( String name) { username=name; } public String getusername() { return username; } } Note: omit the action attribute for <form> if you want the data processed by the object specified in the <jsp:useBean> tag Response.jsp <h1>hello, <jsp:getProperty name=mybean property=username /></h1>

Example Elements

JSP directive passes information to the jsp engine; directives are enclosed in <%@ and %> Fixed template data, typically html or xml, are passed through Jsp actions, or tags, e.g. jsp:useBean tag instantiates the Clock JavaBean on the server Expressions, anything between <%== and %> is evaluated by the jsp engine; e.g. the values of the Day and Year attributes of the Clock bean are returned as strings Scriplet is a small program written in a Java subset; e.g. determining whether it is AM or PM

Jsp Action tags

jsp:useBean, declares the usage of an instance of a java Bean component jsp:setProperty, sets the value of a property in a Bean jsp:getProperty, gets the value of a Bean instance property, converts it to a string jsp:include is a jsp directive causing the associated file to be included jsp tags ARE case sensitive

Why Servlet/JSP? What is an Enterprise Application?


Reliable Scaleable Maintainable Manageable

If you are developing an Enterprise Application for DELL whose daily transction is more than 6 million, or NASDAQ?

Performance? Scalability? Reliability?

Java Beans

Definitions

A reusable software component that can be manipulated visually in a builder tool. (from JavaBean Specification) The JavaBeans API provides a framework for defining reusable, embeddable, modular software components.

Intro to JavaBeans

What are JavaBeans?


Software components written in Java Connect and Configure Components Builder Tools allow connection and configuration of Beans Begins Age of Component Developer Bringing Engineering methods to Software Engineering (e.g. electronics)

The JavaBeans API

Features implemented as extensions to standard Java Class Library Main Component Services

GUI merging Persistence Event Handling Introspection Application Builder Support

User Interface Merging


Containers usually have Menus and/or toolbars Allows components to add features to the menus and/or toolbars Define mechanism for interface layout between components and containers

Persistence

Components can be stored and retrieved Default inherit serialization Can define more complex solutions based on needs of the components

Event Handling

Defines how components interact Java AWT event model serves as basis for the event handling APIs Provides a consistent way for components to interact with each other

Introspection

Defines techniques so components can expose internal structure at design time Allows development tools to query a component to determine member variables, methods, and interfaces Standard naming patterns used Based on java.lang.reflect

Application Builder Support

Provides support for manipulating and editing components at design time Used by tools to provide layout and customizing during design Should be separate from component Not needed at run time

Bean Requirements

Introspection

Exports: properties, methods, events


Subset of components internal state Invoked to execute component code

Properties

Methods

Events (If any needed)


Notification of a change in state User activities (typing, mouse actions, )

Bean Requirements

Customization

Developer can change appearance Save current state so it can be reloaded

Persistence

BeanInfo class

Provides more information using FeatureDescripter objects Subclasses:

BeanDescripter, PropertyDescripter, IndexedPropertyDescripter, EventSetDescripter, MethodDescripter, ParameterDescripter

BeanInfo class

ICON to represent Bean Customizer Class (wizard for set up) Property Editor references List of properties with descriptions List of methods with descriptions Method to reset properties to defaults

The beanbox

Primary task is setting property values Property editors for common types

Set Font Set background/foreground colors Set numeric values Set string values

Creating a Bean

Usually extends Canvas (New window) Can extend Component (lightweight) Needs constructor with no arguments Paint() method used to display getPreferredSize(), getMinimumSize()

For layout manager defaults

get and set methods for each property

Packaging the Bean

Create a JAR file (JavaARchive)

Patterned after tar utility Name: smith/proj/beans/BeanName.class Java-Bean: True (forward slashes even under Windows!)

Create stub manifest


Installing the Bean


Beanbox: copy jar file to /jars directory within the BDK directory Different depending on tool used

The End

64

You might also like