servlets and jsp servlet class typically entends httpservlet servlets override doget() or dopost()...

63
Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or POST PrintWriter class can be used for printing HTML doGet and doPost throw two exceptions ServletException and IOException Servlets are located in /WEB_INF/src/packagename The class files are located in /WEB_INF/classes/packagename The jar files are located in WEB-INF/lib NOTE: You must use packages while buliding servlets http://localhost:8080/servlets/coreservlets.HelloServlet2 Notice that there is a dot between corservlets and HelloServlet2 Utility classes are also placed in the same directory as servlets

Upload: jewel-bond

Post on 26-Dec-2015

252 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Servlets and JSP

•Servlet class typically entends HttpServlet•Servlets override doGet() or doPost() depending on whether the data is being sent by GET or POST•PrintWriter class can be used for printing HTML•doGet and doPost throw two exceptions ServletException and IOException•Servlets are located in /WEB_INF/src/packagename•The class files are located in /WEB_INF/classes/packagename•The jar files are located in WEB-INF/lib•NOTE: You must use packages while buliding servlets•http://localhost:8080/servlets/coreservlets.HelloServlet2•Notice that there is a dot between corservlets and HelloServlet2•Utility classes are also placed in the same directory as servlets

Page 2: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Making a web application directory

• Create a application directory away from server’s installation directory say webAppDir

• Create a WEB-INF directory inside your web application directory

• Html documents go in the top level directory• The web.xml files goes in the WEB-INF subdirectory• Servlets and other classes go in a subdirectory of /WEB-

INF/classes that matches the packagename• Put your jar files in install_dir/WEB-INF/lib• Add webAppDir/WEB-INF/classes to your classpath

Page 3: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Registering the Web Application with the server

• You can register the web application simply by dropping the web application directory in a standard location and then restarting the server

• For tomcat this standard location is:tomcat_install_dir/webapps

Page 4: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

WAR (WEB ARCHIVE) file

• To create a WAR file just change the directory to webAppDir and execute the following command:jar cvf webAppDir.war *

• Most servers let you choose arbitrary prefixes but by default the name of the directory or base name of the war file becomes web application prefix

Page 5: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Deployment Features

• You can develop your servlet and jsp on one server and deploy on another

• Put your development directory in the classpath otherwise you will get “unresolved dymbol” error message when you attempt to compile the servlets that are in packages and make use of classes in the same package

• Include current directory in the classpath otherwise you will only be able to compile packageless classes that are in the top level development directory

Page 6: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Disabling default url and assigning explicit urls in web.xml file

• Use servlet and servlet-mapping elements of web.xml to give a url of the form:

• http://host.webAppPrefix/someServlet

Page 7: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Elements of the deployment descriptor

• <web-app>• <servlet>– <servlet-name>– <servlet-class>

• </servlet>• <servlet-mapping>– <servlet-name>– <url-pattern>

• </servlet-mapping>• </web-app>

Page 8: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

The Role of Web Middleware

• Servlets run on web or application server and act as a middle layer between a request coming from a web browser or other http client and databases or applications on http server

• Their job is to perform the following tasks• Read the explicit data sent by the client• Read the implicit HTTP request data sent by the browser• Generate the result- (this may require talking to the

database,executing an RMI or Corba call, invoking a web service, computing the response directly )

• send the explicit data (i.e. the document) to the client• Send implicit HTTP response data

Page 9: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Basic Servlet Structure• import java.io.*;• import javax.servlet.*;• import javax.servlet.http.*;• public class ServletTemplate extends HttpServlet{• public void doGet(HttpServletRequest request, HttpServletResponse

response)throws ServletException, IOException{• response.setContentType(“text/html”);• PrintWriter out = response.getWriter();• out.println(“Hello World”);• }• }• Note: You need to set response headers before actually returning content

with PrintWriter

Page 10: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Generating HTML with servlet

• import java.io.*;• import javax.servlet.*;• import javax.servlet.http.*;• 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</H1>\n”“</BODY></HTML>”);

• }• }• Note:You need to set response headers before returning any of the content with PrintWriter• Note: The headers can appear in any order and servlets actually buffer the headers and send them all at

once.• Note: Servlets do not necessarily buffer the document itself

Page 11: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Generating output in various formats

• Generating html• response.setContentType(“text/html”);• Generating ms-excel• response.setContentType(“application/vnd.ms-

excel”);• Generating JPEG images• response.setContentType(“image/jpeg”);• Generating XML document• response.setContentType(“text/xml”);

Page 12: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Servlet Packaging

• When you put your serlvets in packages you need to perform the following two additional steps:

1] Insert a package statement in the servlet class file2] Place the files in a subdirectory that matches the

intended package (say coreservlets)name e.g.webAppDir/WEB-INF/classes/coreservlets• Note: Custom classes used by JSP packages should

always be in packages

Page 13: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Using DOCTYPE line in HTML

• The advantage of using doctype line is that:It tells html validators which version of html youare using so they know which specification to

check your document against. These validators are valuable debugging services helping you to catch HTML syntax errors

Page 14: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Servlet using Utility classes for repetitive code

• package coreservlets• import java.io.*;• public class ServletUtilities {• public static final String DOCTYPE = “<!DOCTYPE HTML PUBLIC \” - //W3C//DTD HTML 4.0” + “Transitional//EN\”>”;• public static String headWithTitle(String title){

– return (DOCTYPE + “\n” + “<HTML>\n” + “<HEAD><TITLE>” + title + </TITLE></HEAD>\n” ;

• } • }• package coreservlets• import java.io.*;• import javax.servlet.*;• import javax.servlet.http.*;• public class HelloServlet3 extends HttpServlet{• public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{• response.setContentType(“text/html”);• PrintWriter out = response.getWriter();• String title = “Hello (3)”;• out.println(ServletUtilities . headWithTitle((title) +• “<BODY BGCOLOR=\”#FDF5E6\”>\n” + • “</BODY></HTML>”);• }• }

Page 15: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Servlet LifeCycle

• Servlet is compiled• Servlet is loaded into server’s memory• init() calledNote: init() is where you put one time setup code. This method is for performing

complex setup tasks when the servlet is first loaded but not repeat the task for each request

• service() method called• doGet or doPost calledNote: service method calls doGet() or doPost () depending on the type of service

requests.Note:get request results from a normal request for a url or from an html form that

has no method specified.Note: post request from an html form that specially list post as the method.• destroy() method called• destroy() method gives your servlet a chance to close database connections,

halt background threads, write cookie lists or hit counts to disks and perform other such cleanup activities

Page 16: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Servlet handling Get and Post request identically

• If you have a servlet that needs to handle both GET and POST request identically just have doPost call doGet or vice versa as below:

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

//servlet code}public void doPost(HttpServletRequest

request,HttpServletResponse response)throws ServletException, IOException{

doGet(request,response);}

Page 17: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

The init method• The init() method is called when the servlet is first created and not called again for each user request.• The init() method perform two types of initializations:• general initializations e.g.private int[] numbers = new int[10];public void init()throws ServletException{modTime = System.currentTimeMillis()/1000*1000for(int i=0;i<numbers.length;i++){

numbers[i] = randomNum();}

}• Initializations controlled by initialization parameterspublic void init()throws ServletException{ServletConfig config = getServletConfig()String name = config.getInitParameter(“paramName”)}Note: we get the init param from web.xml<servlet>

<servlet-name>ServletConfigTest</servlet-name><servlet-class>com.javapapers.ServletConfigTest</servlet-class><init-param><param-name>paramName</param-name><param-value>Difference between ServletConfig and ServletContext</param-value></init-param></servlet>

Page 18: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

The SingleThreadModel Interface• Normally the system makes a single instance of your servlet and then

creates a new thread for each user request. If a new request comes in while previous request is still executing multiple threads can concurrently be accessing the same servlet object

• In principle you can prevent multithreaded access by having your servlet implement SingleThreadModel interface as below:

public class YourServlet extends HttpServlet implements SingleThreadModel {

---}• If you implement this interface the system guarantees that there is never

more than one request thread accessing a single instance of your servlet• However the server is permitted to create a pool of multiple instances

each of which handles one request at a time.

Page 19: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Why SingleThreadModel is a poor choice

• Synchronous access can significantly hurt performance especiallyif your servlet is accessed frequently.

• This model permits use of pool of instance instead of queuing up the request to a single instance. If you are using non static instance variables to refer to shared data then each instance has a separate copy of the instance variables, hence the variable is not in a synchronized state and may have different values in different threads. So data may not be shared properly

• If you are using static instance variables to refer to shared data then pool of instance approch provides no advantage whatsoever, multiple requests can still access concurrent data.

Page 20: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Form Data

• http://host/path?user=Marty+Hall&origin=bwi&dest=sfo.

• The part of url after the question mark is known as form data or query data

• Form data can be attached to the end of the url after the question mark for get requests

• Form data can also be sent to the server on a separate line for POST requests.

Page 21: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

HTML Basics

• Use the FORM element to create html form• Use the action attribute of the form element to designate the address of the servlet or the JSP page that

will process the results<FORM ACTION=“/XYZ” METHOD=“GET”></FORM>

• Question mark is added to provided (/XYZ)url and values supplied to name, value pairs make up the additional url

• If ACTION attribute is omitted data is submitted to the url of the current page that will process the results• By using an ACTION URL beginning with a slash you can install the form anywhere in the default web

application, you can move it to another directory or to another machine without editing the html form• Use action urls that are relative not absolute• Place the input elements between the start and end tags of the FORM element and give each element a

NAME• <INPUT type=“text” NAME=“firstName” VALUE=“”>• <INPUT type=“submit” value=“Delete Items From Cart”>• <INPUT type=“password” name=“authenticate_pass”>• <TEXTAREA name=“address” ROWS=“5” COLS=“30”></TEXTAREA>• <INPUT type=“reset”>• <INPUT TYPE=“RADIO” NAME=“cardType” VALUE=“Visa”>VISA<BR>• <INPUT TYPE=“RADIO” NAME=“cardType” VALUE=“MasterCard”>MASTERCARD<BR>

• When the submit button is pressed the url designated by the form’s action is invoked• With Get requests a question mark and name and value pairs are attached to the end of the url• With post request the same data is sent but on a separate line instead of attached to the url.• HTML forms go in the top level directory or in subdirectories other than WEB-INF

Page 22: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Reading Single Values Using getParameter

• To read a request (form) parameter you simply call the getParameter method of HttpServletRequest.

• request.getParameter(“param1”);• You are not required to read the request parameter at any particular

place in your code.• You supply the parameter name exactly as it appeared in html

source code, and you get the result exactly as the end user entered it regardless of how they are sent over the network.

• You use getParameter exactly the same way when data is sent by GET as you do when it is sent by POST.

• An empty String is returned if the parameter exists but has no value• Null is returned if there was no such parameter• Values supplied to getParameter and getParameterValues are case

sensitive

Page 23: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Reading Multiple Values Using getParameterValues

• <SELECT NAME=“language” MULTIPLE><OPTION value=“c”>C

<OPTION value=“c++”>C++ <OPTION value=“java” SELECTED>Java <OPTION value=“lisp”>Lisp

<OPTION value=“perl”>Perl<OPTION value=“smalltalk”>Smalltalk

</SELECT>• If the same parameter might appear in the form data more then once, you

should call getParameterValues() which returns an array of String e.g.• String[] listValues = request.getParameterValues(“language”);

if(listValues != null){for(int i=0; i< listValues.length; i++){

String value = listValues[i];}• The return value of getParameterValues is null for non existant parameter names• It is one element array when the parameter has only a single value\

Page 24: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Looking up Parameter Names• Use getParameterName() to get the parameter list in form of an

Enumeration:• Enumeration paramNames = request.getParameterName();

while(paramName.hasMoreElements()){String paramName = (String)paramNames.nextElement();}

• Enumeration is an interface that guarantees that the implementing class will have hasMoreElements() and nextElement() methods

• Don’t count on get parameter names returning the parameter names in any particular order

• getParameterMap returns a Map

Page 25: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Using Default Values When Parameters are Missing or Malformed

• This section illustrated use of default values• String param = request.getParameter(“someName”);• param= replaceIfMissing(param,”default”)• private String replaceIfMissing(String orig, String replacement){• If(orig == null)||(orig.trim().equals(“”))){• return (replacement)• } else {• return (orig);• }• NOTE: Do not use == to compare the String to “” while checking to

null as the == checks whether the two arguments are the same objects(at the same memory location)

Page 26: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Using StringTokenizer to separate comma separated values

• String languages = request.getParameter(“languages”);• //JAVA,C++,LISP,ADA• makeList(languages)• private String makeList(String listItems){• StringTokenizer tokenizer = new StringTokenizer(listItems,”,”)• String list=“<UL>\n”;• while(tokenizer.hasMoreTokens()){• list = list + “<LI>”+ tokenizer.nextToken() +”\n”;• }• list = list + “</UL>”;• return list;• }

Page 27: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Automatically populating Java Objects from Request Parameters: Form Beans

• In JSP you can do this using the below syntax:• <jsp:useBean id=“entry” class=“coreservlets.SaleEntry” />• <jsp:setProperty name=“entry” property=“*”/>• Note: we can build corresponding utility in Servlets to

automatically populating Java Objects from request parameters using the following code:

• import org.apache.commons.beanutils.BeanUtils• InsuranceInfo bean = new InsuranceInfo();• BeanUtils.populate( bean, request);• We can then get the request parameters using

bean.getName(); etc

Page 28: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Client Request: Http Request Headers

• Client request always moves from client to the server

• Request from a browser consists of the following:1. Get or Post request line (HTTP command usually get or post), along

with http version e.g. HTTP/1.12. Zero or more request headers3. A blank line4. Some query data only in case of post requestsNote: Request headers are sent indirectly by the browsersNote: The serlvets needs to explicitly read the request headers to make

use of this information

Client server

Page 29: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Request Headers

• User the below code to read request headers from a serlvet:• Enumeration headerNames = request.getHeaderNames()• while(headerNames.hasMoreElement){• String headerName = (String)headerNames.nextElement(); • String headerValue = request.getHeader(“headerName”);• }• String userAgent = request.getHeader(“User-Agent”);• request.getCookies - this method yields an array of Cookie objects that were sent by the

browserCookie[] cookies = request.getCookies();

• request.getAuthType() – gives the scheme specified for the authorization header• request.getRemoteUser() – gives the user part• request.getContentLength() – this method returns the value of the content length

header as an int. It gives the number of bytes of data sent.• request.getContentType() – this method returns value of the Content-Type header as a

String. Gives the /mime type of the attached data• getServletContext.getRealPath(“/”) – gives the real directory corresponding to the url

http://host/• request.getMethod() – gives the http request type.• request.getServletPath() – gives the path to the servlet relative to the server’s root

directory.

Page 30: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Request Headers

• Enumeration headerName = request.getHeaderNames()while(headerNames.hasMoreElements()){

String headerName = (String) headers.nextElements()String headerValue = request.getHeader(headerName);

}Note: This gives an enumeration of all header names received on this particular request.• Enumeration specificHeader = request.getHeaders(“Accept-Language”);Note: this gives an Enumeration of all the values of a header which appears multiple times.• request.getMethod() – this returns the main request method normally Get or Post but methods like head, put

and delete are possible.

• request.getRequestURI () - this method returns the part of the url that comes after the host and port but before the form data

• request.getQueryString() – this method returns form data i.e. the part of url after the ?• request.getProtocol() - this method returns the third part of the request line which is generally HTTP/1.0 or

HTTP/1.1Note: this is the first line• request.getLastModified()• request.getRemoteHost - name of the client• request.getRemoteAddress – get the IP address of the client• request.getServerName() – gives the host name of the server machine.• request.getServerPort() – gives the port the server is listening on.• request.getProtocol() – indicates the protocol name and version used in the request line.• getServletContext().getServerInfo() – gives identifying information about the web server.

Page 31: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

SERVER RESPONSE - HTTP STATUS CODE

• server response always moves from the server to the client

• Response from the web server consis of the following:1. Status line – this consists of http version (HTTP/1.1) , a

status code (an integer), very short message corresponding to the status code

2. some response headers – most cases headers are optional except for the Content-Type which specifies the mime type.

3. a blank line4. the document – most responses contain document but

some don’t say when status code 404 is returned.Note: servlets can perform variety of tasks by manipulating the

status line and the response headers.

Client Server

Page 32: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Status codes -

• Http status code is the present in the first line of the request after http version and before actual message

• Servlets don’t need to specify the status code at all. A status code of 200 is automatically set.

• Status code is also set when the servlets use• response.setStatus(), • response.sendRedirect() • response.sendError()

Page 33: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

response.setStatus(),

• this method is used for setting arbitraray status code as below:response.setStatus(response.SC_MOVED_TEMPORARILY); response.setStatus(response.SC_NO_CONTENT);

• be sure to set the status before returning any content with the PrintWriter• servers are allowed to vary the content slightly and clients pay attention only

to the numeric value.• the setStatus method takes an int (the status code) as an argument. but

instead of using explicit numbers, for readibility, for readability and to avoid typos, use constants defind in HttpServletResponse e.g. SC_MOVED_TEMPORARILYSC_NOT_FOUND

• setStatus() does not necessarily mean that you omit the document.• Again remember that if you do send output you have to call set status or

sendError first i.e. you hace to set the status code first.

Page 34: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

response.sendRedirect(url)

• this method throws an IOException• this method sets the status code as 302• it generates a 302 response along with a Location header giving the url of the new

document• the 302 code directs the browser to connect to a new location• The constant representing 302 is SC_MOVED_TEMPORARILY• the browser immediately connects to the new url and no intermediate output is

displayed.• in refresh an intermediate output is displayed.• this is useful when your redirection is based on a certain condition or a certain type

of data.• this is also useful when you want to track the number of visitors to a link. You can

first redirect to your site when you can record some info and then redirect to the real site.This would not be possible with a hyperlink.

• This method also helps you in setting a cookie on the users browser using response.addCookie(Cookie c) which inserts a cookie into the Set-Cookie header

• response.sendRedirect(url) automatically builds a page containing a link to show to old browsers that don’t automatically foollow redirects.

• this method can handle urls automatically turning them into absolute ones.

Page 35: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

response.sendRedirect(url)

• String message = “Incorrect Url”;• if(url !=null){• response.sendRedirect(url)• }else{• response.sendError(response.SC_NOT_FOUND

,message);• }

Page 36: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

response.sendError(int code, String Message)

• this method also throws an IOException• this method sends a status code(usually 404)

along with a shot message that it automatically formatted and sent to the client

• the status code 404 means that the document is not found on the server.

Page 37: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

General Categories-Status Codes

• The status code fall into 5 general categories• 100-199: the codes in the 100s are informational indicating

that the client should respond with some other action• 200-299: the values in the 200s signify that the request was

successful.• 300-399: the values in 300s are used for files that have

moved and usually include a Location header indicating the new address.

• 400-499: values in the 400s indicate an error by the client• 500-599: codes in the 500s signify an error by the

server.This occurs mainly due to syntax error.

Page 38: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Methods to Set HTTP Response Header:

• String encodeRedirectURL(String url)Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.

• String encodeURL(String url)Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.

• boolean containsHeader(String name)Returns a boolean indicating whether the named response header has already been set.

• boolean isCommitted()Returns a boolean indicating if the response has been committed.

• void addDateHeader(String name, long date)Adds a response header with the given name and date-value.

• void addHeader(String name, String value)Adds a response header with the given name and value.

• void addIntHeader(String name, int value)Adds a response header with the given name and integer value.

• void flushBuffer()Forces any content in the buffer to be written to the client.

• void reset()Clears any data that exists in the buffer as well as the status code and headers.

• void resetBuffer()Clears the content of the underlying buffer in the response without clearing headers or status code.

Page 39: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Methods to Set HTTP Response Header:

• void sendError(int sc)Sends an error response to the client using the specified status code and clearing the buffer.

• void sendError(int sc, String msg)Sends an error response to the client using the specified status.

• void setBufferSize(int size)Sets the preferred buffer size for the body of the response.

• void setCharacterEncoding(String charset)Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

• void setLocale(Locale loc)Sets the locale of the response, if the response has not been committed yet.

• void setStatus(int sc)Sets the status code for this response.

Page 40: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Code Snippets

• // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5);

• // Set response content type response.setContentType("text/html"); response.setContentType(“application/vnd.ms-excel");

• response.setContentType(“image/jpeg");• long currentTime = system.currentTimeMillis();

long tenMinutes = 10*60*1000;response.setDateHeader()”Expires,” + currentTime + tenMinutes);

Page 41: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Setting Common Response Headers

• response.setHeader(String headerName, String headerValue)• Sets an arbitrary header. Sets a response header with the given name and value.

• response.setDateHeader(String name, long millisecs)• Sets a response header with the given name and date-value. • Converts milliseconds since 1970 to a date string in GMT format

• response.setIntHeader(String name, int headerValue) • Sets a response header with the given name and integer value.• Prevents need to convert int to String before calling setHeader• response.setIntHeader(“Refresh”,30)• the above code is for page refresh in 30 sec

• addHeader, addDateHeader, addIntHeader • Adds new occurrence of header instead of replacing

Page 42: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Setting Common Response Headers

• void setContentType(String type) • Sets the Content-Type header. • Sets the content type of the response being sent to the client, if the response has not been committed

yet.• Servlets almost always use this. • See table of common MIME types.

• void setContentLength(int len) • Sets the Content-Length header. • Used for persistent HTTP connections. • Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-

Length header.

• void addCookie(Cookie cookie) • Adds a value to the Set-Cookie header. • See separate section on cookies.• Adds the specified cookie to the response.

• void sendRedirect(String location)Sends a temporary redirect response to the client using the specified redirect location URL.

• Sets the Location header (plus changes status code).

Page 43: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Common HTTP 1.1 Response Headers

• Cache-Control (1.1) and Pragma (1.0) • A no-cache value prevents browsers from caching page.

• Content-Disposition• Lets you request that the browser ask the user to save the response • to disk in a file of the given name• Content-Disposition: attachment; filename= file-name

• Content-Encoding • The way document is encoded. See earlier compression example

• Content-Length• The number of bytes in the response. • See setContentLength on previous slide. • Use ByteArrayOutputStream to buffer document before sending it, • so that you can determine size. See discussion of the Connection request

header

Page 44: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Common HTTP 1.1 Response Headers

• Content-Type• The MIME type of the document being returned.• Use setContentType to set this header.

• Expires• The time at which document should be considered out-of-date and thus

should no longer be cached.• Use setDateHeader to set this header.

• Last-Modified• The time document was last changed. • Don’t set this header explicitly; provide a getLastModified method

instead. See lottery number example in book (Chapter 3).

Page 45: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Common HTTP 1.1 Response Headers

• Location• The URL to which browser should reconnect. • Use sendRedirect instead of setting this directly.

• Refresh• The number of seconds until browser should reload page. • Can also include URL to connect to. • See following example.

• Set-Cookie• The cookies that browser should remember. Don’t set this header directly; use addCookie

instead. See next section.

• WWW-Authenticate• The authorization type and realm needed in Authorization header. See security chapters in • More Servlets & JSP

Page 46: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Header Summary

• HTTP is important• Many servlet tasks can only be accomplished through use of HTTP

response headers• Setting response headers–• In general, set with response.setHeader• In special cases, set with • response.setContentType, response.setContentLength,

response.addCookie, response.sendRedirect • Most important response headers you set directly• Cache-Control and Pragma• Content-Disposition• Content-Encoding• Content-Length• Expires• Refresh• WWW-Authenticate

Page 47: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Cookies• Cookies are small bits of textual information that a webserver sends to a browser and that the browser later

returns unchanged when visiting the same website of romain.• Benefits of cookies1. Identifying a user during an e-commerce session.2. Remembering usernames and passwords3. Customizing sites4. Focussing advertisingNote: Http connection is usually closed after each page is sent.Note: Cookies are never interpreted or executed in any way and thus cannot be used to insert viruses or attack

your system.• Automatic session tracking will work whether the client has cookies enabled or not.• In case the cookies are disabled the session tracking is done through url rewriting i.e. the container reads

the session ID straight from the url without using the sesion cookies.• However the container will not automatically append the session ID to the urls that are sent back to the

client inside your jsp pages.• Every url within your application needs to be encoded if its to retain session ID information. This is usually

done through the encode url method of the HttpServletResponse.• Also the c:url method encodes the url specified in its required value attribute appending the session ID if

the client browser is not using cookies and leavesthe url as it was if the client browser is not able to accept a session cookie.

• <H4>Url without parameters <c:url value=“/out.jsp” /></H4>• <c:url value=“/out.jsp” var=“inputUrl” >

<c:param name=“name” value=“John Doe”></c:url><H4>Url with parameters: ${inputUrl}</H4>

Page 48: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Sending cookies to the client

• The cookies are sent by the server to the client

• Creating a cookie object• Setting the maximum age• Send the cookies to the client by placing the

cookies on response headers.Cookie c = new Cookie(“user”,”uid1234”);c.setMaxAge(60*60*24*7);response.addCookie(c)

client server

Page 49: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Reading of cookies from the client by the server

• The cookies are sent by the client and read by the server.

• Call request.getCookies() which returns an array of cookies. If the request contains no cookies then request.getCookies returns null.

• String cookieName=“userID”• Cookie[] cookies = request.getCookies();• if(cookies != null) {

for(int i=0; i<cookies.length;i++){Cookie cookie = cookies[i];if(cookieName.equals(cookie.getName()){doSomethingWith(cookie.getValue());}}

• }• Note: we have use two methods Cookie.getName() and Cookie.getValue()

client server

Page 50: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Code snippet for checking newbie and repeat visitor• boolean newbie = true• Cookie[] cookies = request.getCookies();• if(cookies != null) {

for(int i=0; i<cookies.length;i++){Cookie c = cookies[i];if((c.getName.equals(“repeatVisitor”) ) && (c.getValue().equals(“yes”))){newbie = false;break;

}}

• }• if(newbie){

Cookie returnVisitorCookie = new Cookie(“repeatVisitor”,”yes”); returnVisitorCookie.setMaxAge(60*60*24*365);response.addCookie(returnVisitorCookie );}else{continue}

Page 51: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Setting Cookie Attributes

• You can set various attributes of the cookie after the cookie instantiation using the below setXxx methods.

• These attributes are not set on the cookies that come from browser to the server i.e. you cant call setXxx() while doing request.getCookies

• You will have to set all the parameters again if you want ot modify the cookie and then send the cookie back to the client

• c.setComment(String Comment) – specify a comment associated with the cookie.• c.setDomain(String domainPattern) – set the domain to to which the cookie applies• c.setMaxAge(int lifetime) – set the tage of the cookie that i.e. the time after which

the cookie expires.• c.setPath(String path) – set the path to which the cookie applies.• c.setSecure(boolean secureFlag) – set the flag indicating that the cookie should only

be sent over encrypted connections.• c.setVaue(String cookieValue) – specifies the value associated with the cookie.• c.setVersion(in version) – sets the protocol version with which the cookie complies.Note: You cannot change the name of the cookie once the cookie is created.

Page 52: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Getting Cookie Attributes

• Cookie attributes are not a part of the attributes sent from the browser to the server. They aren’t set on cookies that come from browser to the server.

Page 53: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Difference between session cookies and persistent cookies

• Session have no explicit age set i.e. they are valid only for the current browsing session.

• Persistent queries have their ages set via setMaxAge(int)their max age and you can get their max age using getMaxAge(). these cookies are written to the disc and are valid uptill the time specified.

Page 54: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

How to find cookies with specified names.

• Cookie[] cookies = request.getCookies();• if(cookies != null) {

for(int i=0; i<cookies.length;i++){Cookie cookie = cookies[i];if(cookieName.equals(cookie.getName()){

return (cookie);}

}• }• return null;

Page 55: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Finding cookies with specified values

• Cookie[] cookies = request.getCookies();• if(cookies != null) {

for(int i=0; i<cookies.length;i++){Cookie cookie = cookies[i];if(cookieName.equals(cookie.getName()){

return (cookie.getValue());}

}• }• return (defaultValue);

Page 56: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Session Tracking

• Http is a stateless protocol. • Each time a client retrieves a web page, the client

opens a separate connection to the web server and • the server does not maintain any contextual

information about the client. • Http connection is usually closed after each page is

sent.There are three options for maintaining contextual

information.• Cookies• URL rewriting• Hidden form fields

Page 57: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Session tracking in servlets• Session tracking in servlets is done through HttpSession API. This high level interface is

built on cookies or URL rewriting.• Note: seesion object is a simple hash table for storing user specific data.• Session tracking involves four basic steps:1. Accessing the session object associated with the current request.

HttpSession session = request.getGetSession();2. Looking up information associated with the session.

SomeClass value = (SomeClass )session.getAttribute(“someIdentifier”);if(value=null){SomeClass value = new Someclass(…);session.setAttribute(“someIdentifier” value);}doSomethingWithValue(value);

3. Storing information in a session4. Discardig session data• session.removeAttribute(“key”);// to discard specific value• session.invalidate();// to discard an entire session• session.logout();//invalidate all sessions and logout of the web server.

Page 58: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

request.getSession() basics

• Note: The call to getSession can affect the response. Consequently you are permitted to call getsession only when it will be legal to set HTTP response headers before any document has been sent (i.e. flushed or comitted)

• request.getSession() or request.getSession(true) creates a new session if no session already exists. This is useful if you want to add data to the session regardless of whether data was there already.

• request.getSession(false) returns null if no session already exists. This is useful for printing out information

• HttpSession session = requests.getSession(false);• if(session == null){• printMessageSayingCartIsEmpty();• }else{

extractCartAndPrintMessage}

Page 59: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Session Tracking API

• session.setAttribute(“someIdentifier”,value)• this method associated a value with a name• this method replaces any previous values• the return type is void• session attributes have to be of the type objects. they cannot be null or a primitive like int, double or

boolean• session.removeAttribute(“key”);• return type is void• this method is used to discard the value associated with the specified key.• session.invalidate() ;• this method is used to discard an entire session and all the users session data will be lost not just the

session data that your servlet or JSP page created.• sessions are associated with users and not with individual servlets of JSP pages. So if you invalidate a

session you might be destroying the data that another servlet or JSP page is using.• return type is void• session.logout();• this method is used to log the client out of web server and invalidate all sessions associated with the client• return type is void• session.getAttribute(String name); • this method extracts a previously stored value in the session object. It returns null if no value is associated

with the given object.• This method returns an Object

Page 60: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Session tracking api• session.getAttributeNames();• You can get all the names of all the attribute in a session• return type is Enumeration• session.getId()• this method returns the unique identifier associated with each session• return type is String• public void setMaxInactiveInterval(int seconds);• public void getMaxInactiveInterval()• these methods set the length of time in seconds that a session should go without

access before being automatically invalidated.• sessions become automatically inactive when the amount of time between client

accesses exceeds the time specified by getMaxInactiveInterval• when this happens objects stored in HttpSession objecta re removed.• A negative value specifies that session should never timeout.• Note: timeout is maintained on the server and is not the same as cookie expiration

date• Note: If you quit your browser, your browser level session cookies will be lost and the

browser session is effectively broken

Page 61: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Encoding urls sent to the client

• Url rewriting• In case the cookies are disabled the session tracking is done through url rewriting i.e. the container

reads the session ID straight from the url without using the sesion cookies.• However the container will not automatically append the session ID to the urls that are sent back

to the client inside your jsp pages.• Every url within your application needs to be encoded if its to retain session ID information. This is

usually done through the encode url method of the HttpServletResponse.• In particular if any of your pages contains links back to your site, you have to explicityly add session

data to the url.• There are two situations in which you might use URLs that refer to your own site1. urls are embeded in the web page that your servlet generates. These urls should be passed

through the encodeURL method of the HttpServletResponseString originalURL = someRelativeAbsoluteURLString encodeURL = response.encodeURL(originalURL );

2. While sesing a response.sendRedirect(url) callString originalURL = someURLString encodedURL = response.encodeRedirectURL(originalURL );response.sendRedirect(encodedURL );

Page 62: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

Session tracking with immutable data structure

• Integer accessCount = (Integer)session.getAttribute(“accessCount”);

• if(accessCount == null){• accessCount= new Integer(0);• heading = “Welcome Newcomer”• } else {• accessCount = new integer(accessCount.intValue()+1);• heading = “Welcome back”;• }• session.setAttribute(“accessCount “, accessCount );

Page 63: Servlets and JSP Servlet class typically entends HttpServlet Servlets override doGet() or doPost() depending on whether the data is being sent by GET or

session tracking with mutable data structure

• HttpSession session = request.getSession();• ArrayList previousItems =

(ArrayList)session.getAttribute(“previousItems”);• if(previousItems == null){• previousItems = new Arrayist();• session.setAttribute(“previousItems ”, previousItems );• }• if(newItem != null)• previousItems.add(newItem);