Vous êtes sur la page 1sur 9

Java Servlets

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. Servlet is an opposite of applet as a server-side applet. Applet is an application running on client while servlet is running on server.

Servlet Architecture

Functions of Servlet:
Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit data back to client (HTML) Send the implicit data to client(status codes and response headers)

Servlet Communication

Client
HTML Form

Java-Enabled Web Server call Servlet

Servlet

Web server checks whether the request is of type servlet request or not. Web server determines which servlet has to deal the request. Servlet recievs data using HttpServletRequest obj and sends data using HttpServletResponse obj. Finally sends the data to web browsers

Servlet Architecture
Two packages make up the servlet architecture javax.servlet Contains generic interfaces and classes that are implemented and extended by all servlets javax.servlet.http Contains classes that are extended when creating HTTP-specific servlets

General content of doGet() Method


- set the content type of the response that we are going to send
res.setContentType("text/html"); Create a PrintWriter object to write text to the response message. Output a valid HTML document using PrintWriter Object Close the PrintWriter Object

EXAMPLE PROGRAM
HelloClientServlet.java 1: import java.io.*; 2: import javax.servlet.*; 3: import javax.servlet.http.*; 4: 5: public class HelloClientServlet extends HttpServlet 6: { 7: public void doGet(HttpServletRequest req, 8: HttpServletResponse res) 9: throws ServletException, IOException 10: { 11: res.setContentType("text/html"); 12: PrintWriter out = res.getWriter(); 13: out.println("<HTML><HEAD><TITLE>Hello Client!</TITLE>"+ 14: "</HEAD><BODY>Hello Client!</BODY></HTML>"); 15: out.close(); 16: }

Steps to run Servlet


Compile the servlet Program Copy the resulting .class file to the java servlet capable web browser. Start your server Type http://loacalhost:8080/servlet/helloclientser vlet

Servlet Lifecycle
Server loads Servlets - run init method Servlets Accept Request from Clients and return Data back - run service method Server removes Servlets - run destroy method Server reloads Servlets - run init method
No Concurrency Issue Server runs init only once, not per request

service must be thread-safe - multiple service method at a time if that is impossible, servlet must implement SingleThreadModel interface destroy must be thread-safe - when server runs destroy, other threads might be accessing shared resources

Vous aimerez peut-être aussi