12

Click here to load reader

Servlets

Embed Size (px)

Citation preview

Page 1: Servlets

Servlets

By: Abdalla Mahmoud1.

ContentsServlets .............................................................................................. 1

1. Introduction................................................................................... 22. First Servlet ................................................................................... 2

2.1. Servlet class. ............................................................................ 22.2. Deployment Descriptor .............................................................. 3

2.3. Packaging the Web Module ............................................................ 43. Analyzing the Request ..................................................................... 4

3.1. Analyzing Request Headers......................................................... 43.2. Analyzing Request Parameters .................................................... 43.3. Analyzing Agent's Cookies .......................................................... 5

4. Sending the Response ..................................................................... 64.1. Sending Response Headers......................................................... 64.2. Sending Response Content ......................................................... 64.3. Sending Agent Cookies .............................................................. 7

5. Hoax Example - Add Two Numbers.................................................... 85.1. HTML Form............................................................................... 8

5.1.1. Packaging Static Resources ................................................... 85.2. Process Servlet ......................................................................... 8

5.2.1. Mapping Process Servlet ....................................................... 96. Hoax Example Revisited - Separate Controller from View ..................... 9

6.1. Process Servlet ........................................................................106.2. View Servlet ............................................................................10

7. HTTP Sessions...............................................................................117.1. Creating HTTP Session ..............................................................117.2. Sharing Data ...........................................................................12

1. http://www.abdallamahmoud.com/.

1

Page 2: Servlets

1. Introduction

Servlets are web components that generate dynamic content to user agents. Like otherenterprise components, servlets are deployed on and managed by the application server.Any Java EE compliant application server provides an implementation for HTTP server. JBosscomes with Apache Tomcat embedded as the HTTP server.

Servlets are java classes that extend HttpServlet. The HttpServlet is a generic prototype fora typical web component. The Java EE developer extends the class to create custom webcomponents. The class, by default, provides seven methods that can be overriden to satisfyevery possible HTTP method:

HTTP Methods Methods Provided by the HttpServlet Class.

void doGet(HttpServletRequest req, HttpServletResponse resp)void doPost(HttpServletRequest req, HttpServletResponse resp)void doDelete(HttpServletRequest req, HttpServletResponse resp)void doHead(HttpServletRequest req, HttpServletResponse resp)void doOptions(HttpServletRequest req, HttpServletResponse resp)void doPut(HttpServletRequest req, HttpServletResponse resp)void doTrace(HttpServletRequest req, HttpServletResponse resp)

The role of a servlet is to analyze the request and respond to it.

2. First Servlet

2.1. Servlet class.

The servlet class is a java class that extends the HttpServlet class and overrides one ormore HTTP methods methods in the super class. All servlet classes should be located underWEB-INF/classes/ in the web module.

2

Page 3: Servlets

file: WEB-INF/classes/webapp/MyFirstServlet.java

package webapp ;

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

public class MyFirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

PrintWriter out = response.getWriter() ;out.println("<html>") ;out.println("<head>") ;out.println("<title>First Servlet</title>") ;out.println("</head>") ;out.println("<body>") ;out.println("<h1>My First Servlet</h1>") ;out.println("Hello world") ;

}

}

2.2. Deployment Descriptor

Every web module is accossiated with a deployment descriptor file that describes thecomponents of the web application. The configuration file should be located in WEB-INF/web.xml in the web module.

file: WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet><servlet-name>MyFirstServlet</servlet-name><servlet-class>webapp.MyFirstServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>MyFirstServlet</servlet-name><url-pattern>/foo</url-pattern>

</servlet-mapping>

3

Page 4: Servlets

</web-app>

2.3. Packaging the Web Module

Unlike business modules, web modules are packaged into war files (Web ARchive) rather thanjar files (Java ARchive). Same command is used here:

Command Prompt

C:\workspace\> jar cf foo.war WEB-INF/classes/webapp/*.class WEB-INF/web.xml

3. Analyzing the Request

The web server is responsible for listening to agent connections, read and understandHTTP request, then encapsulates it structured in an object. The object is then passed to theservlet's HTTP method's method as an argument to the request parameter. The followingsections show the request object and how it can be used in different contexts.

3.1. Analyzing Request Headers

Request headers can be retrieved using method String getHeader(String name).

file: WEB-INF/classes/webapp/MyFirstServlet.java

package webapp ;

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

public class MyFirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

String agent = request.getHeader("User-Agent") ;

}

}

3.2. Analyzing Request Parameters

Request parameters can be retrieved using method String getParameter(String name).

file: WEB-INF/classes/webapp/MyFirstServlet.java

4

Page 5: Servlets

package webapp ;

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

public class MyFirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

int id = Integer.parseInt(request.getParameter("id")) ;PrintWriter out = response.getWriter() ;out.println("You have requested topic with id:" + id) ;

}

}

3.3. Analyzing Agent's Cookies

Agent cookies can be retrieved using method Cookie[] getCookies(). Objects of classCookie used to represent an agent's cookie. Cookie's name and value are encapsulated inmethods getName() and getValue() respectively.

file: WEB-INF/classes/webapp/MyFirstServlet.java

package webapp ;

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

public class MyFirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

Cookie[] cookies = request.getCookies() ;for(int i = 0 ; i < cookies.length ; i++) {

String cookieName = cookies[i].getName() ;String cookieValue = cookies[i].getValue() ;

//process the cookie}

}

5

Page 6: Servlets

}

4. Sending the Response

The web server is responsible for sending response to agents, then close the connection.It provides a response object that encapsulates different response data and actions.Thefollowing sections show the response object and how it can be used in different contexts.

4.1. Sending Response Headers

Response headers can be added to the response using the method void addHeader(Stringname, String value).

file: WEB-INF/classes/webapp/MyFirstServlet.java

package webapp ;

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

public class MyFirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

response.addHeader("Content-Type", "text/html");

}

}

4.2. Sending Response Content

Response content can be written to the agent using the response's output stream. It can beretrieved using the method PrintWriter getWriter().

file: WEB-INF/classes/webapp/MyFirstServlet.java

package webapp ;

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

public class MyFirstServlet extends HttpServlet {

6

Page 7: Servlets

public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

//get a reference to the stream of the output to the agentPrintWriter out = response.getWriter() ;

//write to the stream >> the outputout.println("<html>") ;out.println("<head>") ;out.println("<title>First Servlet</title>") ;out.println("</head>") ;out.println("<body>") ;out.println("<h1>My First Servlet</h1>") ;out.println("Hello world") ;out.println("</body>") ;out.println("</html>") ;

}

}

4.3. Sending Agent Cookies

Cookies can be sent to be added or modified at the agent using the methodaddCookie(Cookie cookie). A cookie object should be passed encapsulating the cookie'sdata. A cookie object can be instantiated using constructor Cookie(String name, Stringvalue).

file: WEB-INF/classes/webapp/MyFirstServlet.java

package webapp ;

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

public class MyFirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

response.addCookie(new Cookie("user_id", "125"));

}

}

7

Page 8: Servlets

5. Hoax Example - Add Two Numbers

Our target is to develop a web application that allows a user to add two numbers. Theapplication will consist of the following resources:

• A form page (page.html).• A servlet that process and display the output (ProcessServlet).

5.1. HTML Form

file: page.html

<html>

<head><title>Add Two Numbers</title></head>

<body>

<form method="POST" action="/process">Number 1:<input type="textfield" name="num1"/><br/>Number 2:<input type="textfield" name="num2"/><br/><input type="submit" value="Add"/>

</form>

</body>

</html>

5.1.1. Packaging Static Resources

Static resources such as html pages (.html) and images (.jpeg, .png, .gif) are packages inthe root of the web archive, and need not to be mapped in the .

5.2. Process Servlet

file: WEB-INF/classes/webapp/ProcessServlet.java

package webapp ;

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

public class ProcessServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

8

Page 9: Servlets

float num1 = Float.parseFloat(request.getParameter("num1")) ;float num2 = Float.parseFloat(request.getParameter("num2")) ;float result = num1 + num2 ;String message = "Result = " + result ;

PrintWriter out = response.getWriter() ;

out.println("<html>") ;out.println("<head>") ;out.println("<title>Result by Process Servlet</title>") ;out.println("</head>") ;out.println("<body>") ;out.println(message) ;out.println("</body>") ;out.println("</html>") ;

}

}

5.2.1. Mapping Process Servlet

Add the following mappings in the web.xml file:

file: WEB-INF/web.xml

...

<servlet><servlet-name>ProcessServlet</servlet-name><servlet-class>webapp.ProcessServlet</servlet-class>

</servlet>

<servlet-mapping><servlet-name>ProcessServlet</servlet-name><url-pattern>/process</url-pattern>

</servlet-mapping>

...

6. Hoax Example Revisited - Separate Controller from View

Our target is to redevelop the previous web application so as to consist of the followingresources:

• A form page (page.html).• A servlet that process and display the output (ProcessServlet).• Another servlet that display the output (ViewServlet).

9

Page 10: Servlets

The web application will work in the following scenario: the user requests page.html, fillthe form, post the data. The data is processed by ProvessServlet, which will forward therequest to the ViewServlet to view the data. Although a trivial example, it's the mainconcept in separating the controller from the view in web design patterns.

6.1. Process Servlet

file: WEB-INF/classes/webapp/ProcessServlet.java

package webapp ;

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

public class ProcessServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

float num1 = Float.parseFloat(request.getParameter("num1")) ;float num2 = Float.parseFloat(request.getParameter("num2")) ;float result = num1 + num2 ;

//set attribute to be shared with the delegates

request.setAttribute("result", result) ;

//create a request dispatcher from the request objectRequestDispatcher rd = request.getRequestDispatcher("/view") ;//forward the request passing request and response objectsrd.forward(request, response) ;

}

}

6.2. View Servlet

file: WEB-INF/classes/webapp/ViewServlet.java

package webapp ;

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

public class ViewServlet extends HttpServlet {

10

Page 11: Servlets

public void doPost(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

float result = (Float) request.getAttribute("result") ;String message = "Result = " + result ;

PrintWriter out = response.getWriter() ;

out.println("<html>") ;out.println("<head>") ;out.println("<title>Result by Process Servlet</title>") ;out.println("</head>") ;out.println("<body>") ;out.println(message) ;out.println("</body>") ;out.println("</html>") ;

}

}

7. HTTP Sessions

As we saw later, HTTP is a stateless protocol. To overcome this in stateful web applications,session concept should be implemented. In Java EE, session concept is abstracted andprovided via the HttpSession interface. A reference to a session object can obtained usingthe method HttpSession getSession() in the request object.

7.1. Creating HTTP Session

file: WEB-INF/classes/webapp/MyFirstServlet.java

package webapp ;

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

public class MyFirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws IOException, ServletException {

HttpSession session = request.getSession() ;session.setAttribute("user_id", "505") ;

}

11

Page 12: Servlets

}

7.2. Sharing Data

Data can be shared using the method void setAttribute(String name, Object value).Any other page can retrieve shared data using the method Object getAttribute().

12