servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfservlets are java programs that can be run...

57
Servlets

Upload: others

Post on 16-Apr-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Servlets

Page 2: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Static Pages

request

response

Web browser

Web server

Page 3: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Dynamic Pages

request request

responseresponse

ServletJSPASP

ServletJSPASP

Web browser

Web server

Page 4: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

What is a Servlet?

Servlets are Java programs that can be run dynamically in a Web ServerServlets are a server-side technologyA Servlet is an intermediating layer between an HTTP request of a client and the Web server

Page 5: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

What do Servlets do?

• Read data sent by the user (e.g., form data)

• Look up other information about request in the HTTP request (e.g. authentication data, cookies, etc.)

• Generate the results (may do this by talking to a database, file system, etc.)

• Format the results in a document (e.g., make it into HTML)

• Set the appropriate HTTP response parameters (e.g. cookies, content- type, etc.)

• Send the document to the user

Page 6: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Supporting Servlets

The Web server must support Servlets (since it must run the Servlets):

Apache TomcatSun’s Java System Web Server and Java System Application ServerIBM's WebSphere Application ServerAllaire Jrun – an engine that can be added to IIS, PWS, old Apache Web servers etc…Oracle Application ServerBEA WebLogic

Page 7: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

The Servlet InterfaceJava provides the interface ServletSpecific Servlets implement this interfaceWhenever the Web server is asked to invoke a specific Servlet, it activates the method service() of an instance of this Servlet

service(request,response)

MyServlet

(HTTP)request

(HTTP)response

Page 8: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Servlet Hierarchy

service(ServletRequest, ServletResponse)

YourOwnServlet

HttpServlet

Generic Servlet

Servlet

doGet(HttpServletRequest , HttpServletResponse)

doPost(HttpServletRequestHttpServletResponse)

doPutdoTrace

Page 9: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Class HttpServlet

Class HttpServlet handles requests and responses of HTTP protocolThe service() method of HttpServlet checks the request method and calls the appropriate HttpServlet method: doGet, doPost, doPut, doDelete, doTrace,

doOptions or doHeadThis class is abstract

Page 10: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Creating a Servlet

Extend the class HTTPServlet

Implement doGet or doPost (or both)

Both methods get:HttpServletRequest: methods for getting form (query) data, HTTP request headers, etc.

HttpServletResponse: methods for setting HTTP status codes, HTTP response headers, and get an output stream used for sending data to the client

Usually implement doPost by calling doGet, or vice-versa

Page 11: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Returning HTMLBy default a text response is generated (text/plain)

In order to generate HTMLTell the browser you are sending HTML, by setting the Content-Type header (text/html)

Modify the printed text to create a legal HTML page

You should set all headers before writing the document content.

Page 12: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

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

public class HelloWorld extends HttpServlet {public void doGet(HttpServletRequest req, HttpServletResponseres) throws ServletException, IOException {

res.setContentType("text/html");PrintWriter out = res.getWriter();

out.println("<HTML><HEAD><TITLE>Hello World</TITLE></HEAD>");

out.println(“<BODY><H1>Hello World</H1></BODY></HTML>");

out.close();}

}

Page 13: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an
Page 14: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Configuring the ServerAfter you code your servlet, you need to compile it to generate class files.When your Servlet classes are ready, you have to configure the Web server to recognize it.This includes:

Telling the Server that the Servlet existsPlacing the Servlet class file in a place known to the serverTelling the server which URL should be mapped to the Servlet

These details are server specific.

Page 15: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Deploying Servlets on the J2EE Application Server

Step 1: Start the J2EE Application Server.Step 2: Start the Deployment Tool (deploytool).Step 3: Assemble the J2EE Application.

Create a new J2EE application (.ear file)Create a new Web component (.war file). Specify the context root for the J2EE application.Specify an alias for the J2EE application.Verify your J2EE application.Deploy your J2EE applicationTest your J2EE application.

Page 16: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 1: Create New Enterprise Application (.ear file)

Page 17: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 1: Create New Enterprise Application (Contd.)

Page 18: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component

Web components (Java servlets and associated classes, JavaServer Pages, HTML pages, and other relevant Web resources like images) are bundled into a Web Archive (WAR) file

Page 19: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 20: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 21: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 22: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 23: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 24: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 25: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 26: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 27: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 28: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 2: Create New Web Component (Contd.)

Page 29: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 3: Specify the Root Context(where the deploytool will put the web components)

Page 30: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 4: Verify Your Application

Page 31: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 5: Specify Aliases

Page 32: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 6: Deploy Your Application

Page 33: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Step 7: Run Your Application

Page 34: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

The Big Picture

.class

.jar

.class.html

.jsp

.jpeg

J2EE Enterprise Application (EAR file)J2EE Web Component (WAR file)

Page 35: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Getting Information From the Request

Page 36: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Getting HTTP Data

Values of the HTTP request can be accessed through the HttpServletRequest objectGet the value of the header hdr usinggetHeader("hdr") of the request argumentGet all header names: getHeaderNames()Methods for specific request information: getCookies, getContentLength, getContentType,getMethod, getProtocol, etc.

Page 37: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

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

public class ShowRequestHeaders extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");PrintWriter out = response.getWriter();String title = "Servlet Example:

Showing Request Headers";

Page 38: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

out.println("<HTML><HEAD><TITLE>" + title + "</TITLE></HEAD>" +"<BODY BGCOLOR=\"#AACCAA\" TEXT=\"#990000\">\n" +"<H1 ALIGN=CENTER>" + title + "</H1>\n" +"<B>Request Method: </B>" +request.getMethod() + "<BR>\n" +"<B>Request URI: </B>" +request.getRequestURI() + "<BR>\n" +"<B>Request Protocol: </B>" +request.getProtocol() + "<BR><BR>\n" +"<TABLE BORDER=1 ALIGN=CENTER>\n" +"<TR BGCOLOR=\"#88AA88\">\n" +"<TH>Header Name<TH>Header Value");

Page 39: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Enumeration headerNames = request.getHeaderNames();

while(headerNames.hasMoreElements()) {String headerName =(String)headerNames.nextElement();out.println("<TR><TD>" + headerName);out.println("<TD>“ + request.getHeader(headerName));

}out.println("</TABLE>\n</BODY></HTML>");

}

public void doPost(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {doGet(request, response);

}}

Page 40: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an
Page 41: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

User Input in HTMLUsing HTML forms, we can pass parameters to web applications<form action=… method=…> …</form> comprises a single form • action: the address of the application to which

the form data is sent• method: the HTTP method to use when

passing parameters to the application (e.g.GET or POST)

Page 42: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

GET Example

<HTML><FORM method="GET"

action="http://www.google.com/search"><INPUT name="q" type="text"><INPUT type="submit"> <INPUT type="reset"></FORM></HTML>

http://www.google.com/search?q=servlets

Page 43: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

POST Example<HTML> <FORM method=“POST“

action="http://www.google.com/search"><INPUT name=“q" type="text"><INPUT type="submit"><INPUT type="reset">

</FORM> </HTML>

POST /search HTTP/1.1

Host: www.google.com

Content-type: application/x-www-form-urlencoded

Content-length: 10

<empty-line>

q=servlets

Page 44: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Getting the Parameter Values

To get the value of a parameter named x:req.getParameter("x")

where req is the service request argumentIf there can be multiple values for the parameter:

req.getParameterValues("x")To get parameter names:

req.getParameterNames()

Page 45: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

<HTML><HEAD><TITLE>Sending Parameters</TITLE>

</HEAD><BODY BGCOLOR="#CC90E0"><H1 ALIGN="LEFT">Please enter the parameters</H1>

<FORM ACTION=“SetColors”METHOD=“GET”>

<TABLE><TR><TD>Background color:</TD><TD><INPUT TYPE="TEXT" NAME="bgcolor"></TD></TR><TR><TD>Font color:</TD><TD><INPUT TYPE="TEXT" NAME="fgcolor"></TD></TR><TR><TD>Font size:</TD><TD><INPUT TYPE="TEXT" NAME="size"></TD></TR></TABLE> <BR><INPUT TYPE="SUBMIT" VALUE="Show Page">

</FORM></BODY></HTML>

Page 46: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an
Page 47: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

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

public class SetColors extends HttpServlet {public void doGet(HttpServletRequest request,

HttpServletResponse response)throws ServletException, IOException {

response.setContentType("text/html");PrintWriter out = response.getWriter();String bg = request.getParameter("bgcolor");String fg = request.getParameter("fgcolor");String size = request.getParameter("size");

Page 48: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

out.println("<HTML><HEAD><TITLE>Set Colors Example" + "</TITLE></HEAD>");

out.println("<BODY text='" + fg + "' bgcolor='" + bg + "'>");

out.println("<H1>Set Colors Example</H1>");out.println("<FONT size='" + size + "'>");out.println("You requested a background color " +

bg + "<P>");out.println("You requested a font color " +

fg + "<P>");out.println("You requested a font size " +

size + "<P>");out.println("</FONT></BODY></HTML>");

}}

Page 49: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an
Page 50: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Handling Post

public void doPost(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);}

You don't have to do anything different to read POST data instead of GET data!!

<FORM ACTION=“SetColors”METHOD=“POST”> …

Page 51: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Creating the Response of the Servlet

Page 52: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Setting the Response Status

Use the following HttpServletResponsemethods to set the response status:- setStatus(int sc)

Use when there is no error, like 201 (created) - sendError(sc), sendError(sc, message)

Use in erroneous situations, like 400 (bad request)The server may return a formatted message

- sendRedirect(String location)Redirect to the new location

Page 53: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Setting the Response Status

Class HTTPServletResponse has static integer variables for popular status codes

for example:SC_OK(200), SC_NOT_MODIFIED(304), SC_UNAUTHORIZED(401), SC_BAD_REQUEST(400)

Status code 200 (OK) is the default

Page 54: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Setting Response Headers

Use the following HTTPServletResponsemethods to set the response headers:- setHeader(String hdr, String value),

setIntHeader(String hdr, int value)Override existing header value

- addHeader(String hdr, String value), addIntHeader(String hdr, int value)

The header is added even if another header with the same title exists

Page 55: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

Specific Response HeadersClass HTTPServletResponse provides setters for some specific headers:- setContentType- setContentLength

automatically set if the entire response fits inside the response buffer

- setDateHeader- setCharacterEncoding

Page 56: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

More Header Methods

• containsHeader(String header)Check existence of a header in the response

• addCookie(Cookie)• sendRedirect(String url)

automatically sets the Location header Do not write information to the response after sendError or sendRedirect

Page 57: Servlets - wmich.edualfuqaha/cs595/lectures/lecture14.pdfServlets are Java programs that can be run dynamically in a Web Server Servlets are a server-side technology A Servlet is an

ReferenceRepresentation and Management of Data on the Internet (67633), Yehoshua Sagiv, The Hebrew University - Institute of Computer Science.