Request Scope

  1. Request Scope is maintained by ServletRequest object
  2. Request Scope will start at the time of Request object creation. i.e just before starting service() method and ends at the time of Request obj destruction(i.e just after completing service() method)
  3. The information stored in the request scope is by default available to all components which are processing the request.

ServletRequest interface defines the following methods for attribute Management in request scope.

  1. public void setAttribute(String name,Object value)
  2. To add an attribute. If the specified attribute is already available then old value will be placed with new value.

  3. public Object getAttribute(String name)
  4. Returns the value associated with specified attribute is not available then this method returns null.

  5. public void removeAttribute(String name)
  6. public Enumeration getAttributeNames()

Example:

Display number of requests from a particular IP address.
  1. Create servlet that extends HttpServlet
  2. Create web.xml
  3. Create war file and deploy web application
  4. Output of web application
  5. Download web application

Create servlet

package com.java2learn;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestFromIP extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out=resp.getWriter();
		ServletContext context=getServletContext();
		String ipaddress=req.getRemoteAddr();

		Integer count=(Integer)context.getAttribute("ipaddress");

		if(count==null) {
		   count=1;
		}else{
		   count++;
		}
		context.setAttribute("ipaddress",count);
		out.println("no.of hits::"+ ipaddress+"----"+ count);
	}
}

Create web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>WebApp</display-name>

	<servlet>
		<servlet-name>RequestFromIP</servlet-name>
		<servlet-class>com.java2learn.RequestFromIP</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>RequestFromIP</servlet-name>
		<url-pattern>/ipRequest</url-pattern>
	</servlet-mapping>
</web-app>

Final Application structure

FinalApplicationIP

Create war file and Deploy the application

Output:

noOfHits

Download Project: WebApp