Java by API/javax.servlet.http/HttpServletRequest — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 17:43, 31 мая 2010

HttpServletRequest: getAuthType()

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AuthenticationSnoop extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<HTML><BODY>");
    out.println("<H1>This is a password protected resource</H1>");
    out.println("<PRE>");
    out.println("User Name: " + req.getRemoteUser());
    String name = (req.getUserPrincipal() == null) ? null : req.getUserPrincipal().getName();
    out.println("Principal Name: " + name);
    out.println("Authentication Type: " + req.getAuthType());
    out.println("Is a Manager: " + req.isUserInRole("manager"));
    out.println("</PRE>");
    out.println("</BODY></HTML>");
  }
}





HttpServletRequest: getCookies()

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShoppingCartViewerCookie extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    String sessionid = null;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("sessionid")) {
          sessionid = cookies[i].getValue();
          break;
        }
      }
    }
    // If the session ID wasn"t sent, generate one.
    // Then be sure to send it to the client with the response.
    if (sessionid == null) {
      sessionid = generateSessionId();
      Cookie c = new Cookie("sessionid", sessionid);
      res.addCookie(c);
    }
    out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
    out.println("<BODY>");
    // Cart items are associated with the session ID
    String[] items = getItemsFromCart(sessionid);
    // Print the current cart items.
    out.println("You currently have the following items in your cart:<BR>");
    if (items == null) {
      out.println("<B>None</B>");
    } else {
      out.println("<UL>");
      for (int i = 0; i < items.length; i++) {
        out.println("<LI>" + items[i]);
      }
      out.println("</UL>");
    }
    // Ask if they want to add more items or check out.
    out.println("<FORM ACTION=\"/servlet/ShoppingCart\" METHOD=POST>");
    out.println("Would you like to<BR>");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
    out.println("</FORM>");
    // Offer a help page.
    out.println("For help, click ");
    out.println("</BODY></HTML>");
  }
  private static String generateSessionId() throws UnsupportedEncodingException {
    String uid = new java.rmi.server.UID().toString(); // guaranteed unique
    return URLEncoder.encode(uid,"UTF-8"); // encode any special chars
  }
  private static String[] getItemsFromCart(String sessionid) {
    return new String[]{"a","b"};  
  }
}





HttpServletRequest: getHeader( ) by Accept-Charset

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Hello extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    String acceptLanguage = req.getHeader("Accept-Language");
    String acceptCharset = req.getHeader("Accept-Charset");
    res.getOutputStream().println("acceptLanguage: " + acceptLanguage);
    res.getOutputStream().println("acceptCharset" + acceptCharset);
  }
}





HttpServletRequest: getHeader( ) by Accept-Language

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Hello extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    String acceptLanguage = req.getHeader("Accept-Language");
    String acceptCharset = req.getHeader("Accept-Charset");
    res.getOutputStream().println("acceptLanguage: " + acceptLanguage);
    res.getOutputStream().println("acceptCharset" + acceptCharset);
  }
}





HttpServletRequest: getHeaderNames()

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 HeaderSnoop extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    out.println("Request Headers:");
    Enumeration names = req.getHeaderNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      Enumeration values = req.getHeaders(name); // support multiple values
      if (values != null) {
        while (values.hasMoreElements()) {
          String value = (String) values.nextElement();
          out.println(name + ": " + value);
        }
      }
    }
  }
}





HttpServletRequest: getHeaders(String name)

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 HeaderSnoop extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    out.println("Request Headers:");
    Enumeration names = req.getHeaderNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      Enumeration values = req.getHeaders(name); // support multiple values
      if (values != null) {
        while (values.hasMoreElements()) {
          String value = (String) values.nextElement();
          out.println(name + ": " + value);
        }
      }
    }
  }
}





HttpServletRequest: getPathInfo()

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileLocation extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    if (req.getPathInfo() != null) {
      out.println("The file \"" + req.getPathInfo() + "\"");
      out.println("Is stored at \"" + req.getPathTranslated() + "\"");
    }
    else {
      out.println("Path info is null, no file to lookup");
    }
  }
}





HttpServletRequest: getPathTranslated()

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileLocation extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    if (req.getPathInfo() != null) {
      out.println("The file \"" + req.getPathInfo() + "\"");
      out.println("Is stored at \"" + req.getPathTranslated() + "\"");
    }
    else {
      out.println("Path info is null, no file to lookup");
    }
  }
}





HttpServletRequest: getQueryString()

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 QueryString extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    out.println("Query String:");
    out.println(req.getQueryString());
    out.println();
    out.println("Request Parameters:");
    Enumeration e = req.getParameterNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      String values[] = req.getParameterValues(name);
      if (values != null) {
        for (int i = 0; i < values.length; i++) {
          out.println(name + " (" + i + "): " + values[i]);
        }
      }
    }
  }
}





HttpServletRequest: getRemoteUser()

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PersonalizedServlet extends HttpServlet {
  Hashtable accesses = new Hashtable();
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    String remoteUser = req.getRemoteUser();
    if (remoteUser == null) {
      out.println("Welcome!");
    }
    else {
      out.println("Welcome, " + remoteUser + "!");
      Date lastAccess = (Date) accesses.get(remoteUser);
      if (lastAccess == null) {
        out.println("This is your first visit!");
      }
      else {
        out.println("Your last visit was " + accesses.get(remoteUser));
      }
      if (remoteUser.equals("User A")) {
        out.println("HI.");
      }
      accesses.put(remoteUser, new Date());
    }
  }
}





HttpServletRequest: getRequestURI()

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ClientPullMove extends HttpServlet {
  static final String NEW_HOST = "http://www.jexp.ru";
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    String newLocation = NEW_HOST + req.getRequestURI();
    res.setHeader("Refresh", "10; URL=" + newLocation);
    out.println("The requested URI has been moved to a different host.<BR>");
    out.println("Its new location is " + newLocation + "<BR>");
    out.println("Your browser will take you there in 10 seconds.");
  }
}





HttpServletRequest: getSession()

import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ManualInvalidate extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    HttpSession session = req.getSession();
    // Invalidate the session if it"s more than a day old or has been
    // inactive for more than an hour.
    if (!session.isNew()) { // skip new sessions
      Date dayAgo = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
      Date hourAgo = new Date(System.currentTimeMillis() - 60 * 60 * 1000);
      Date created = new Date(session.getCreationTime());
      Date accessed = new Date(session.getLastAccessedTime());
      if (created.before(dayAgo) || accessed.before(hourAgo)) {
        session.invalidate();
        session = req.getSession(); // get a new session
      }
    }
  }
}





HttpServletRequest: getUserPrincipal()

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AuthenticationSnoop extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<HTML><BODY>");
    out.println("<H1>This is a password protected resource</H1>");
    out.println("<PRE>");
    out.println("User Name: " + req.getRemoteUser());
    String name = (req.getUserPrincipal() == null) ? null : req.getUserPrincipal().getName();
    out.println("Principal Name: " + name);
    out.println("Authentication Type: " + req.getAuthType());
    out.println("Is a Manager: " + req.isUserInRole("manager"));
    out.println("</PRE>");
    out.println("</BODY></HTML>");
  }
}





HttpServletRequest: isRequestedSessionIdFromCookie()

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionSnoop extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    HttpSession session = req.getSession();
    Integer count = (Integer) session.getAttribute("count");
    if (count == null)
      count = new Integer(1);
    else
      count = new Integer(count.intValue() + 1);
    session.setAttribute("count", count);
    out.println("<HTML><HEAD><TITLE>Session Count</TITLE></HEAD>");
    out.println("<BODY><H1>Session Count</H1>");
    out.println("You"ve visited this page " + count
        + ((count == 1) ? " time." : " times."));
    out.println("<P>");
    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }
    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");
    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie()
        + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");
    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click ");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren"t supported.");
    out.println("</BODY></HTML>");
  }
}





HttpServletRequest: isRequestedSessionIdFromURL()

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionSnoop extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    HttpSession session = req.getSession();
    Integer count = (Integer) session.getAttribute("count");
    if (count == null)
      count = new Integer(1);
    else
      count = new Integer(count.intValue() + 1);
    session.setAttribute("count", count);
    out.println("<HTML><HEAD><TITLE>Session Count</TITLE></HEAD>");
    out.println("<BODY><H1>Session Count</H1>");
    out.println("You"ve visited this page " + count
        + ((count == 1) ? " time." : " times."));
    out.println("<P>");
    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }
    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");
    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie()
        + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");
    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click ");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren"t supported.");
    out.println("</BODY></HTML>");
  }
}





HttpServletRequest: isRequestedSessionIdValid()

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionSnoop extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    HttpSession session = req.getSession();
    Integer count = (Integer) session.getAttribute("count");
    if (count == null)
      count = new Integer(1);
    else
      count = new Integer(count.intValue() + 1);
    session.setAttribute("count", count);
    out.println("<HTML><HEAD><TITLE>Session Count</TITLE></HEAD>");
    out.println("<BODY><H1>Session Count</H1>");
    out.println("You"ve visited this page " + count
        + ((count == 1) ? " time." : " times."));
    out.println("<P>");
    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }
    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");
    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie()
        + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");
    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click ");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren"t supported.");
    out.println("</BODY></HTML>");
  }
}





HttpServletRequest: isUserInRole(String arg0)

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AuthenticationSnoop extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<HTML><BODY>");
    out.println("<H1>This is a password protected resource</H1>");
    out.println("<PRE>");
    out.println("User Name: " + req.getRemoteUser());
    String name = (req.getUserPrincipal() == null) ? null : req.getUserPrincipal().getName();
    out.println("Principal Name: " + name);
    out.println("Authentication Type: " + req.getAuthType());
    out.println("Is a Manager: " + req.isUserInRole("manager"));
    out.println("</PRE>");
    out.println("</BODY></HTML>");
  }
}





ServletRequest: getReader()

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UTF8 extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    try {
      BufferedReader reader = req.getReader();
      res.setContentType("text/html; charset=UTF-8");
      PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);
      // Read and write 4K chars at a time
      // (Far more efficient than reading and writing a line at a time)
      char[] buf = new char[4 * 1024]; // 4Kchar buffer
      int len;
      while ((len = reader.read(buf, 0, buf.length)) != -1) {
        out.write(buf, 0, len);
      }
      out.flush();
    } catch (Exception e) {
      getServletContext().log(e, "Problem filtering page to UTF-8");
    }
  }
}





ServletRequest: getRequestDispatcher(String arg0)

import java.io.IOException;
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 DispatchServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
 
    // Forward to a display page
    String display = "/servlet/SearchView";
    RequestDispatcher dispatcher = req.getRequestDispatcher(display);
    dispatcher.forward(req, res);
  }
}