Introduction to Servlets Allen Day
Notes This is a training NOT a presentation Please ask questions Prerequisites – Basic Java and HTML skills – Installed LDSTech IDE (or other equivalent)
Overview Basic Web App Architecture HTTP CGI Overview Understanding the role of servlets Maven Project Directory Structure Servlet Life Cycle Event Listeners Servlet Filters
Basic Web App Architecture Request WWW Browser Web Server Response
Basic Web App Architecture Request WWW Browser Web Server Response
HTTP Request WWW Browser Web Server Response HTTP
HTTP Request Methods GET POST HEAD TRACE PUT DELETE OPTIONS CONNECT
GET Method Simple The total amount of characters in a GET is limited. The data you send with the GET is appended to the URL, so whatever you send is exposed.
POST Method Used for complex requests, such as form submissions. Parameters are stored in the body.
CGI Overview 1. Submit Form WWW Browser Web Server Application Server 2. Call CGI 3. CGI Program’s response 4. CGI Program’s response
CGI Process Form use strict; main(); sub main () { my $query; read( STDIN, $query, $ENV{CONTENT_LENGTH} ); = split( /&/, $query ); my %pairs = (); foreach my $item ) { my ($key, $value) = split( /=/, $item ); $key =~ tr/+/ /; $value =~ tr/+/ /; $key =~ s/%([A-F\d]{2})/chr(hex($1))/ieg; $value =~ s/%([A-F\d]{2})/chr(hex($1))/ieg; $pairs{$key} = $value; } my $name = $pairs{name}; my $ = $pairs{ }; my $machine = $ENV{REMOTE_HOST}; print( STDOUT "Content-Type:text/html\r\n" ); print( STDOUT "Status: 200 Ok\r\n" ); print( STDOUT "\r\n" ); print( STDOUT <<HTML ); Form example output welcome Hi $name of $ from machine $machine HTML }
CGI Issues May intentionally or unintentionally leak information about the host system that will help hackers break in. Scripts may be vulnerable to attacks in which the remote user tricks them into executing commands. Susceptible to Buffer overflows. Insufficient input validation. Each call to a CGI script runs as a separate process. Simultaneous CGI requests cause the CGI script to be copied and loaded into memory as many times as there are requests.
Servlet Overview Client Servlet ContainerWeb Server Request Response
Advantages of Servlets Servlets stay loaded and client requests for a Servlet resource are handled as separate threads of a single running Servlet. A servlet can be run by a servlet engine in a restrictive environment, called a sandbox. This reduces security risks.
Maven Project Directory Structure
pom.xml <project xmlns=" xmlns:xsi=" xsi:schemaLocation=" org.lds.training MyServlet war 1.0 MyServlet Maven Webapp junit test
web.xml <web-app xmlns=" xmlns:xsi=" xsi:schemaLocation=" version="2.5"> Welcome to Java Stack Training Introduction to Servlets HelloWorldServlet org.lds.training.HelloWorldServlet HelloWorldServlet /HelloWorldServlet
Lab 1: Simple Servlet #Lab_1_Simple_Servlet
Servlet Life Cycle 1.Load class 2.Instantiate servlet 3.init() 4.service() 5.destroy()
Servlet Container Client Servlet ContainerWeb Server
Servlet Container 1.Loads the servlet class. 2.Creates an instance of the servlet class. 3.Initializes the servlet instance by calling the init method. 4.Handles client requests. 5.If the container needs to remove the servlet it finalizes the servlet by calling the servlet's destroy method.
Servlet Container Communications support Lifecycle Management Multithreading Support Declarative Security JSP Support
Servlet Container Web Server request response Servlet
Servlet Container requestresponse Servlet thread
Servlet Container request response Servlet thread Service()
Servlet Container response Servlet thread Service() doGet()
Servlet Container Web Server request response X
HttpServletRequest MethodDescription getCookies()Obtain array of cookies getMethod()RETURNS the HTTP method (GET or POST) getPathInfo()Returns any extra path information for the request URI getRemoteUser()Gets the name of the user making the request (provided by HTTP authentication) getSession()Returns the current valid session associated with this request or creates a new session
HttpServletResponse MethodDescription addCookie()Adds the specified cookie to the response encodeURL()Encodes the URL by including the session id in it if needed sendError()Sends an error response to the user with the specified error code sendRedirect()Sends a redirect request to the user
Servlet Class Extends java.servlet.http.HttpServlet init() service() doGet() doPost() destroy()
init() public void init() throws ServletException { // custom code goes here } public void init(ServletConfig config) throws ServletException { super.init(ServletConfig) // custom code goes here }
service() public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Custom code goes here }
doGet() public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Custom Code goes here }
doPost() public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Custom Code goes here }
destroy() public void destroy() { // custom code goes here }
Lab 2: Page Hit Counter #Lab_2_Page_Hit_Counter
Event Listeners
javax.servlet.ServletContextListener javax.servlet.ServletContextAttributeListener javax.servlet.http.HttpSessionListener javax.servlet.http.HttpSessionAttributeListener
Event Listeners javax.servlet.ServletContextListener javax.servlet.ServletContextAttributeListener javax.servlet.http.HttpSessionListener javax.servlet.http.HttpSessionAttributeListener
web.xml org.lds.training.HelloWorldSessionListener org.lds.training.HelloWorldContextListener
Servlet Filters
Client Servlet ContainerWeb Server Request Response Filter 1 Filter 2
web.xml timer filter.TimerFilter timer myservlet /mypath/*
Lab 3: Login Filter #Lab_3_Login_Filter
Credit where credit is due Head First Servlets & JSP Bryan Basham, Kathy Sierra & Bert Bates More Servlets and JavaServer Pages Marty Hall Images from the Microsoft Clip Art gallery