31
The Servlet Technology Inside Servlets Writing Servlet Applications

Lecture 2

Embed Size (px)

Citation preview

Page 1: Lecture 2

The Servlet Technology

Inside Servlets

Writing Servlet Applications

Page 2: Lecture 2

2

What Is a Servlet?

“A servlet is a server-side Java replacement for CGI scripts and programs. Servlets are much faster and more efficient than CGI and they let you unleash the full power of Java on your web server, including back-end connections to databases and object repositories through JDBC, RMI, and CORBA”

– Atlanta Java Users Group (http://www.ajug.org/meetings/jun98.html)

Page 3: Lecture 2

Ways to use Servlet

A simple way:

Servlet can process data which was POSTed over HTTPS using an HTML FORM, say, an order-entry, and applying the business logic used to update a company's order database.

Page 4: Lecture 2

A simple servlet

Page 5: Lecture 2

Some other uses:

Since servlets handle multiple requests concurrently, the requests can be synchronized with each other to support collaborative applications such as on-line conferencing.

One could define a community of active agents, which share work among each other. The code for each agent would be loaded as a servlet, and the agents would pass data to each other.

One servlet could forward requests other servers. This technique can balance load among several servers which mirror the same content.

Page 6: Lecture 2

Server-side Java for the web

a servlet is a Java program which outputs an html page; it is a server-side technology

browserweb server

HTTP Request

HTTP Response

Server-side Request

Response Header +Html file

Java Servlet

Java Server Page

servlet container (engine) - Tomcat

Page 7: Lecture 2

Servlet Structure

Java Servlet Objects on Server SideManaged by Servlet Container

Loads/unloads servlets

Directs requests to servlets

Request → doGet()

Each request is run as its own thread

Page 8: Lecture 2

8

A servlet Is a Server-side Java Class Which Responds to Requests

service()

doPost()

doGet()

doPut()

doDelete()

Page 9: Lecture 2

Servlet Basics

Packages: javax.servlet, javax.servlet.http

Runs in servlet container such as TomcatTomcat 4.x for Servlet 2.3 APITomcat 5.x for Servlet 2.4 APIServlet lifecyclePersistent (remains in memory between requests) Startup overhead occurrs only onceinit() method runs at first requestservice() method for each requestdestroy() method when server shuts down

Page 10: Lecture 2

Web App with Servlets

HEADERS

BODY

Servlet

doGet()……

GET …

Servlet Container

Page 11: Lecture 2

11

Life-cycle of a servlet

init()service()destroy()It can sit there simply servicing requests with no start up overhead, no code compilation. It is FASTIt may be stateless – minimal memory

Page 12: Lecture 2

Client - Server - DB

Page 13: Lecture 2

5 Simple Steps for Java Servlets

1. Subclass off HttpServlet2. Override doGet(....) method3. HttpServletRequest getParameter("paramName")

4. HttpServletResponseset Content Typeget PrintWritersend text to client via PrintWriter

5. Don't use instance variables

Page 14: Lecture 2

14

HTTP: Request & Response

Client sends HTTP request (method) telling server the type of action it wants performedGET methodPOST method

Server sends response

Page 15: Lecture 2

15

Http: Get & Post

GET methodFor getting information from serverCan include query string, sequence with additional information for GET, appended to URLe.g. Http://www.whoami.Com/Servlet/search?Name=Inigo&ID=1223344

Page 16: Lecture 2

16

Http: Get & Post

POST methoddesigned to give information to serverall information (unlimited length) passed as part of request body

• invisible to user• cannot be reloaded (by design)

Page 17: Lecture 2

Interaction with Client

HttpServletRequestString getParameter(String)Enumeration getParameters(String[])

HttpServletResponseWriter getWriter()ServletOutputStream getOutputStream()

Handling GET and POST Requests

Page 18: Lecture 2

10/12/11 G53ELC: Servlets 18

HttpServlet

Implements Servlet Receives requests and sends responses to a web browserMethods to handle different types of HTTP requests:doGet() handles GET requestsdoPost() handles POST requestsdoPut() handles PUT requestsdoDelete() handles DELETE requests

Page 19: Lecture 2

19

HttpServlet Request Handling

Page 20: Lecture 2

20

Handling HttpServlet Requests

service() method not usually overriddendoXXX() methods handle the different request typesNeeds to be thread-safe or must run on a STM (SingleThreadModel) Servlet Enginemultiple requests can be handled at the same time

Page 21: Lecture 2

21

Simple Counter Example

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

public class SimpleCounter extends HttpServlet{

int count = 0;

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

{res.setContentType(“text/plain”);PrintWriter out = res.getWriter();count++;out.println(“This servlet has been accessed “ + count +

“ times since loading”);}

}

Page 22: Lecture 2

22

Multithreading solutions

Synchronize the doGet() methodpublic synchronized void doGet(HttpServletRequest req, HttpServletResponse res)

servlet can’t handle more than one GET request at a time

Synchronize the critical sectionPrintWriter out = res.getWriter();synchronized(this){

count++;out.println(“This servlet has been accessed “ + count + “ times since loading”);

}

Page 23: Lecture 2

Forms and Interaction

<form method=get action=“/servlet/MyServlet”>GET method appends parameters to action URL:/servlet/MyServlet?userid=Jeff&pass=1234This is called a query string (starting with ?)

Username: <input type=text name=“userid” size=20>Password: <input type=password name=“pass” size=20><input type=submit value=“Login”>

Page 24: Lecture 2

Assignment 2: Get Stock Price

Page 25: Lecture 2
Page 26: Lecture 2

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

public class RequestHeaderExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getHeader(headerName); out.println(name + “ = “ + value ); } }}

RequestHeaderExample.java

Page 27: Lecture 2

Accessing Request Components

getParameter("param1")getCookies() => Cookie[]getContentLength()getContentType()getHeaderNames()getMethod()

Page 28: Lecture 2

Environment Variables

JavaServlets do not require you to use the clunky environment variables used in CGIIndividual functions:PATH_INFO req.getPathInfo()REMOTE_HOST req.getRemoteHost()QUERY_STRING req.getQueryString()…

Page 29: Lecture 2

Setting Response Components

Set status first!setStatus(int)

HttpServletResponse.SC_OK...sendError(int, String)sendRedirect(String url)

Page 30: Lecture 2

Setting Response Components

Set headerssetHeader(…)setContentType(“text/html”)

Output bodyPrintWriter out = response.getWriter();out.println("<HTML><HEAD>...")

Page 31: Lecture 2

31

Install Web Server on your machine such as Tomcat, Appache, ..

Create Home Page as CV which should contains: Your Name as title You Image in the right hand side Your previous courses listed in Table

Another linked Page for Accepting your friends which should contains form to accept your friends information: Name (Text Field) Birth of Date (Text Field) Country ( Drop Down List) E-mail ( Text Field) Mobile ( Text Field) Gender (Radio Button with Male or Female) Save request of friends into file