RequestDisplay.java Source code

Java tutorial

Introduction

Here is the source code for RequestDisplay.java

Source

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

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

public class RequestDisplay extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, java.io.IOException {

        ContextObject obj = (ContextObject) request.getAttribute("com.java2s.RequestObject");
        //display the attribute's Map keys
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
        out.println("<html><head><title>Request Attribute</title></head><body>");
        out.println("<h2>Request attribute values</h2>");
        if (obj != null)
            out.println(obj.getValues());
        out.println("</body></html>");

    } //end doGet

}

//ContextObject.java

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) i.next() + "<br>");
        }

        return buf.toString();

    }

    public String toString() {

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

}