Request binder : Do Get Do Post « Servlets « Java

Request binder

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestBinder extends HttpServlet {

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

    //bind an object to the servlet context
    ContextObject contextObj = new ContextObject();
    contextObj.put(request.getRemoteAddr(), "" + new java.util.Date());
    request.setAttribute("com.java2s.RequestObject", contextObj);

    //better display something
    RequestDispatcher dispatcher = request
    dispatcher.forward(request, response);

  } //end doGet



class ContextObject {

  private Map map;

  public ContextObject() {

    map = Collections.synchronizedMap(new HashMap());

  public void put(Object key, Object value) {

    if (key == null || value == null)
      throw new IllegalArgumentException(
          "Invalid parameters passed to ContextObject.put");

    map.put(key, value);

  public Map getMap() {

    return map;


  public String getValues() {

    StringBuffer buf = new StringBuffer("");
    Set set = map.keySet();

    synchronized (map) {

      Iterator i = set.iterator();
      while (i.hasNext())
        buf.append((String) + "<br>");

    return buf.toString();


  public String toString() {

    return getClass().getName() + "[ " + map + " ]";



Related examples in the same category

1.Simple servlet: Copyright
2.Print various CGI variables that have been requested by the servlet
3.Print all header information available from the client
4.Request header viewer
5.Request display
6.Servlet Request Listener
7.Client auto refresh
8.Get Request Parameters in a Servlet