Java/Servlets/Do Get Do Post

Материал из Java эксперт
Версия от 06:11, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Get Request Parameters in a Servlet

 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Main extends HttpServlet {
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    Enumeration en = request.getParameterNames();
    while (en.hasMoreElements()) {
      String paramName = (String) en.nextElement();
      out.println(paramName + " = " + request.getParameter(paramName) + "<br/>");
    }
  }
}





Print all header information available from the client

 
/*
 * <servlet> <servlet-name>PrintHeader </servlet-name>
 * <servlet-class>PrintHeader </servlet-class> </servlet>
 * 
 * <servlet-mapping> <servlet-name>PrintHeader </servlet-name>
 * <url-pattern>/PrintHeader </url-pattern> </servlet-mapping>
 * 
 *  
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PrintHeader extends HttpServlet {
  /**
   * doGet implementation, calls printHeader function
   * 
   * @param request
   * @param response
   * @throws IOException
   * @throws ServletException
   *  
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    printHeader(request, response);
  }
  /**
   * doPost implementation, calls printHeader function
   * 
   * @param request
   * @param response
   * @throws IOException
   * @throws ServletException
   *  
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    printHeader(request, response);
  }
  /**
   * Prints client header information that is available
   * 
   * @param request
   * @param response
   * @throws IOException
   * @throws ServletException
   *  
   */
  public void printHeader(HttpServletRequest request,
      HttpServletResponse response) throws IOException, ServletException {
    String headers = null;
    String htmlHeader = "<HTML><HEAD><TITLE> Request Headers</TITLE></HEAD><BODY>";
    String htmlFooter = "</BODY></HTML>";
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Enumeration e = request.getHeaderNames();
    out.println(htmlHeader);
    out.println("<TABLE ALIGN=CENTER BORDER=1>");
    out.println("<tr><th> Header </th><th> Value </th>");
    while (e.hasMoreElements()) {
      headers = (String) e.nextElement();
      if (headers != null) {
        out.println("<tr><td align=center><b>" + headers + "</td>");
        out.println("<td align=center>" + request.getHeader(headers)
            + "</td></tr>");
      }
    }
    out.println("</TABLE><BR>");
    out.println(htmlFooter);
  }
}





Print various CGI variables that have been requested by the servlet

 
//*
 * <servlet> 
 * <servlet-name>PrintCGI </servlet-name> 
 * <servlet-class>PrintCGI
 * </servlet-class> 
 * </servlet>
 * 
 * <servlet-mapping> 
 * <servlet-name>PrintCGI </servlet-name>
 * <url-pattern>/PrintCGI </url-pattern> 
 * </servlet-mapping>
 */
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PrintCGI extends HttpServlet {
  /**
   * doGet implementation, calls printCGIValues
   * 
   * @param request
   * @param response
   * @throws IOException
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    printCGIValues(request, response);
  }
  /**
   * doPost implementation, calls printCGIValues
   * 
   * @param request
   * @param response
   * @throws IOException
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    printCGIValues(request, response);
  }
  /**
   * Prints CGI Environment Variables in a table
   * 
   * @param request
   * @param response
   * @throws IOException
   */
  public void printCGIValues(HttpServletRequest request,
      HttpServletResponse response) throws IOException {
    String headers = null;
    String htmlHeader = "<HTML><HEAD><TITLE> CGI Environment Variables </TITLE></HEAD><BODY>";
    String htmlFooter = "</BODY></HTML>";
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println(htmlHeader);
    out.println("<TABLE ALIGN=CENTER BORDER=1>");
    out.println("<tr><th> CGI Variable </th><th> Value </th>");
    out.println("<tr><td align=center>Authentication Type</td>");
    out.println("<td align=center>" + request.getAuthType() + "</td></tr>");
    out.println("<tr><td align=center>Content Type</td>");
    out.println("<td align=center>" + request.getContentType()
        + "</td></tr>");
    out.println("<tr><td align=center>Content Type Length</td>");
    out.println("<td align=center>" + request.getContentLength()
        + "</td></tr>");
    out.println("<tr><td align=center>Query String</td>");
    out.println("<td align=center>" + request.getMethod() + "</td></tr>");
    out.println("<tr><td align=center>IP Address</td>");
    out.println("<td align=center>" + request.getRemoteAddr()
        + "</td></tr>");
    out.println("<tr><td align=center>Host Name</td>");
    out.println("<td align=center>" + request.getRemoteHost()
        + "</td></tr>");
    out.println("<tr><td align=center>Request URL</td>");
    out.println("<td align=center>" + request.getRequestURI()
        + "</td></tr>");
    out.println("<tr><td align=center>Servlet Path</td>");
    out.println("<td align=center>" + request.getServletPath()
        + "</td></tr>");
    out.println("<tr><td align=center>Server"s Name</td>");
    out.println("<td align=center>" + request.getServerName()
        + "</td></tr>");
    out.println("<tr><td align=center>Server"s Port</td>");
    out.println("<td align=center>" + request.getServerPort()
        + "</td></tr>");
    out.println("</TABLE><BR>");
    out.println(htmlFooter);
  }
}





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, java.io.IOException {
    //bind an object to the servlet context
    ContextObject contextObj = new ContextObject();
    contextObj.put(request.getRemoteAddr(), "" + new java.util.Date());
    request.setAttribute("com.jexp.RequestObject", contextObj);
    //better display something
    RequestDispatcher dispatcher = request
        .getRequestDispatcher("/displayAttr");
    dispatcher.forward(request, response);
  } //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 + " ]";
  }
}





Request display

 
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.jexp.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 + " ]";
  }
}





Request header viewer

 
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestHeaderView extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    //get an Enumeration of all the request header names
    Enumeration e = request.getHeaderNames();
    //display
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>Request Header View</title></head><body>");
    out.println("<h2>Request Headers</h2>");
    String header = null;
    while (e.hasMoreElements()) {
      header = (String) e.nextElement();
      //getHeader returns null if a request header of that name does not
      // exist in the request
      out.println("<strong>" + header + "</strong>" + ": "
          + request.getHeader(header) + "<br>");
    }
    out.println("</body></html>");
  } //end doGet
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    doGet(request, response);
  }
}





Servlet Request Listener

 
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
public class ReqListener implements ServletRequestListener {
  private static long reqCount;
  public void requestInitialized(ServletRequestEvent sre) {
    ServletContext context = sre.getServletContext();
    ServletRequest request = sre.getServletRequest();
    synchronized (context) {
      context
          .log("Request for "
              + (request instanceof HttpServletRequest ? ((HttpServletRequest) request)
                  .getRequestURI()
                  : "Unknown") + "; Count=" + ++reqCount);
    }
  }
  public void requestDestroyed(ServletRequestEvent sre) {
  }
}





Simple servlet: Copyright

 
/*
  <servlet>
        <servlet-name>Copyright</servlet-name>
        <servlet-class>Copyright</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Copyright</servlet-name>
        <url-pattern>/Copyright</url-pattern>
    </servlet-mapping>
*/
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Copyright extends HttpServlet {
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException,
      java.io.IOException {
    java.io.PrintWriter out = response.getWriter();
    out.println("Copyright&copy; 2003-2004 Java Source and Support.");
    out.close();
  }
}