csc 2720 building web applications java servlet (part 1) the basics

24
CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Upload: james-brooks

Post on 29-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

CSC 2720Building Web Applications

Java Servlet (Part 1)The Basics

Page 2: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Overview of Server-Side Scripting1. Client sends a request via HTTP protocol

A HTTP request consists of A request method: GET, POST, HEAD, PUT, etc. A URI that identifies the requested resource Header fields A body (which can be empty)

2. Web server locates the corresponding server-side script and dispatches the HTTP request to the script.

3. The server-side script processes the data embedded in the HTTP request and produces a HTTP response.

4. The web server returns the generated HTTP response to the client.

Page 3: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Server-Side Scripting with Java Servlet Servlets are the Java platform technology of choice for exte

nding and enhancing Web servers.

A servlet is a module of Java code that is executed at the server side to process a request and generates a response based on that request. A servlet is not a standalone Java program nor it is a CGI-script writt

en in Java. A servlet is an object with a specific interface and it can only be "exe

cuted" in a special environment known as servlet container.

The Servlet technology offers a framework to write, deploy, and run servlets. It also serves as a foundation for other Java-based server-side tech

nologies. e.g., JSP and JSF.

Page 4: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Servlet Application Architecture

Browser ServletContainer

Servlet

Static Content

HTTP Request

HTTP Response

Browser HTTPServer

Servlet

Static Content

HTTP Request

HTTP Response

ServletContainer

Page 5: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Servlet Container A servlet container is a specialized web server o

r a component of a web server that supports servlet execution.

It is responsible for Managing the lifecycle of servlets (load, initialize, dispat

ch requests, destroy, etc.) Mapping a URL to a particular servlet Providing access controls to the hosted resources Providing services defined in the Servlet API such as m

anaging sessions, etc.

Page 6: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

The Tomcat Container Apache Tomcat 6.0 Supports Servlet 2.5 and JavaServer Pages 2.1

The one bundled with NetBeans 6.0 is version 6.0.14

http://jakarta.apache.org/tomcat/

If you want to test your Servlets (without NetBeans), typically you have to Install and configure the Tomcat web server Set environment variables such as CLASSPATH Create proper directory structure for your web applications

Page 7: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

How a Servlet WorkReceiveRequest

SendResponse

Is servletloaded?

Is servletup to date?

Load Servlet

Process Request

No

No

Yes

Yes

Loaded by the container the first time a servlet is requested

Handle the request

Resides in memory and waits for future requests A servlet may get

reloaded if modified

Page 8: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

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

public class HelloWorldServlet extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("<html><head><title>Hello World Servlet</title>" +"</head><body>" +"Hello World" +"</body></html>"

);out.close();

}}

123456789101112131415161718192021

A servlet that output "Hello World".

Page 9: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Writing a Servlet

1. Create a public class as a subclass of javax.servlet.http.HttpServlet

2. Import the Java Servlet packages javax.servlet.* javax.servlet.http.*

3. Override one or more doXXX() methods to process HTTP request and to produce HTTP response Typically, we override doGet(), doPost(), or both

Page 10: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Writing a Servlet

4. Within the doGet() or doPost() methods, we typically perform the following tasks:

a. Retrieve the data from HTTP request e.g.: Form data, parameters encoded in the URL,

cookies, HTTP header fields

b. Process the retrieved data

c. Generate the content of the HTTP response: e.g.: Add header fields, set cookies, generate HTML

codes, etc.

Page 11: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

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

public class ServletEx1 extends HttpServlet {

public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException {

// Retrieving value of parameters named "x" and "y" String x = req.getParameter("x"); String y = req.getParameter("y");

String sum = "Undefined"; // Process the data (calculate the sum) try { int v1 = Integer.parseInt(x); int v2 = Integer.parseInt(y); sum = "" + (v1 + v2); // Store the result as string } catch (Exception e) { }

12345678910111213141516171819202122

A servlet that adds the value of two parameters.

Page 12: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

PrintWriter out = res.getWriter();

out.println( "<html><head><title>ServletEx1: Adding 2 #'s</title>" + "</head><body>" );

out.println("Value of x is: " + x + "<br />"); out.println("Value of y is: " + y + "<br />"); out.println("Their sum is: " + sum + "<br />"); out.println("</body></html>"); out.close();

} // End of doGet()} // end of class ServletEx1

123456789101112131415161718192021

Page 13: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Getting Parameters Instance methods of HttpServletRequest for retrieving

parameter values:String getParameter(String paramName)

Use this method when a parameter has at most one value

String [] getParameterValues(String paramName)

Use this method if a parameter can have multiple values

Both methods return null if the specified parameter does not exist.

Instance methods of HttpServletRequest for retrieving all parameter names:java.util.Enumeration getParameterNames()

Page 14: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Getting Parameters

Parameter names are case sensitive.

Parameter values are retrieved as strings. You need to write code to convert them from strings to respective

data types.

Always validate the parameter values before processing the data Users may omit or mistype the values in a form. Hackers can bypass HTML form and JavaScript validation and

generate HTTP POST/GET request programmatically.

Page 15: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Servlets Packages Package: javax.servlet

Contains many interfaces and abstract classes for protocol independent generic servlets

Package: javax.servlet.http Contains interfaces and abstract

classes for servlets that understand HTTP protocols

Extends from the interfaces and classes used in the generic servlets

Ref: Java Servlet 2.3 API documentation

Servlet

GenericServlet

HttpServlet

MyServlet

implemented by

extended by

extended by

Page 16: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Characteristics of Servlet Class Every servlet directly or indirectly implements the

javax.servlet.Servlet interface.

That means, every servlet contains the following methods: void init(ServletConfig config) void service(ServletRequest req, ServletResponse res) void destroy() ServletConfig getServletConfig() String getServletInfo()

A servlet container interacts with a servlet through these methods.

Page 17: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Servlet Life Cycles Initialization

The servlet's init() method is called once in a servlet's lifetime when a servlet is first loaded.

If an exception is thrown or uncaught in init(), the servlet won't run.

Handling RequestsThe servlet's service() method is called whenever a se

rvlet is needed to service a request.A servlet can serve multiple requests concurrently (The co

ntainer create threads to serve multiple requests)

TerminationThe servlet's destroy() method is called once when the

servlet is being unloaded from memory.

Page 18: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Servlet Life Cycles init()

Overload this method only if you need to perform a task once in a servlet's lifecycle.

e.g.: To open a database connection

destroy() Overload this method only if you need to perform some cleanup tasks

before a servlet is being unloaded from memory. e.g.: To close a database connection or to remove some temporary fil

es

service() Overload this method only if you need to handle ALL types of HTTP r

equests (GET, POST, DELETE, HEADER, PUT, etc.) To handle a specific type of HTTP requests, we can just overload one

of doXXX() methods.

Page 19: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

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

public class MyPrimitiveServlet extends HttpServlet {public void doPost(HttpServletRequest request,

HttpServletResponse response)throws ServletException, IOException

{// Handle POST request

}

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException

{// Handle GET request

}}

12345678910111213141516171819

HttpServlet implemented the method service() which dispatches various types of request (GET, POST, etc.) to the proper doXXX() methods respectively.

Subclass should override at least one of the doXXX() methods.

Page 20: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

HttpServletRequest object To obtain the data encapsulated in a HTTP request

Form data, cookies, header fields, body contents Query string and additional path info embedded in the URL

To obtain additional info about a request e.g.: The name of authentication scheme used

To obtain info about the requester e.g.: Client's host name, IP address, etc.

To obtain session information associated with the current request

To carry additional data between servlets when a request is dispatched or forwarded from one servlet to another.

Page 21: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

HttpServletResponse object To send data in the request body

This object contains an output buffer which can be obtained via

ServletOutputStream getOutputStream()

Suitable for writing binary data

java.io.PrintWriter getWriter()

Suitable for writing texts

Only one of the above methods can be called. Data written to the output buffer is sent to the client in the request

body.

To add header fields, add/set cookies, set content type, set status code, send error code and error message, send redirection instruction

Page 22: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

ServletConfig object The ServletConfig object can be obtained by calling getServletConfig()

The object contains some info specified in web application deployment/configuration file – web.xml Servlet's name

Parameters to be passed to the servlet e.g., URL of the database

A ServletContext object

Page 23: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

ServletContext object A ServletContext object contains APIs for a servlet to c

ommunicate with its servlet container. e.g.:

Get server info and version of the servlet API Write to the log file Get the MIME type of a file Dispatch requests

There is one context per "web application" per servlet container. A "web application" is a collection of servlets and content installed u

nder a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.

Servlets belong to the same application can share data through the ServletContext object.

Page 24: CSC 2720 Building Web Applications Java Servlet (Part 1) The Basics

Summary Fundamentally, all server-side scripts work in the following manner:

Obtains data from a HTTP request Processes the data Produces HTTP response

Java Servlet technology provides a framework to write, deploy and execute servlets.

Serlvet APIs help programmers to Obtain data from a HTTP request (HttpServletRequest) Obtain info from the servlet container (ServletConfig and ServletCont

ext) Set data in a HTTP response (HttpServletResponse) Manage session information (HttpServletRequest and HttpSession)

References: "Java for the Web with Servlets, JSP, and EJB" by Budi Kurniawan Wiki: Java Servlets (http://en.wikipedia.org/wiki/Java_Servlet) Servlet Essentials (http://www.novocode.com/doc/servlet-essentials/)