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

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

Текущая версия на 14:35, 31 мая 2010

HttpServletResponse: addCookie(Cookie arg0)

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"};  
  }
}





HttpServletResponse: encodeURL(String url)

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>");
  }
}





HttpServletResponse.SC_BAD_REQUEST

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 GoTo extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    // Determine the site where they want to go
    String site = req.getPathInfo();
    String query = req.getQueryString();
    // Handle a bad request
    if (site == null) {
      res.sendError(res.SC_BAD_REQUEST, "Extra path info required");
    }
    // Cut off the leading "/" and append the query string
    // We"re assuming the path info URL is always absolute
    String url = site.substring(1) + (query == null ? "" : "?" + query);
    // Log the requested URL and redirect
    log(url); // or write to a special file
    res.sendRedirect(url);
  }
}





HttpServletResponse.SC_MOVED_TEMPORARILY

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SiteSelector extends HttpServlet {
  Vector<String> sites = new Vector<String>();
  Random random = new Random();
  public void init() throws ServletException {
    sites.addElement("http://www.jexp.ru");
    sites.addElement("http://www.servlets.ru");
    sites.addElement("http://java.sun.ru/products/servlet");
    sites.addElement("http://www.google.ru");
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    int siteIndex = Math.abs(random.nextInt()) % sites.size();
    String site = sites.elementAt(siteIndex);
    res.setStatus(res.SC_MOVED_TEMPORARILY);
    res.setHeader("Location", site);
  }
}





HttpServletResponse: sendError(int arg0, String arg1)

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 Buffering extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setBufferSize(8 * 1024); // 8K 
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    int size = res.getBufferSize(); // returns 8096 or greater
    log("The default buffer size is " + size);
    out.println("The client won"t see this");
    res.reset();
    out.println("Nor will the client see this!");
    res.reset();
    out.println("And this won"t be seen if sendError() is called");
    if (req.getParameter("param") == null) {
      res.sendError(res.SC_BAD_REQUEST, "param needed");
    }
  }
}





HttpServletResponse: sendRedirect(String arg0)

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 GoTo extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    // Determine the site where they want to go
    String site = req.getPathInfo();
    String query = req.getQueryString();
    // Handle a bad request
    if (site == null) {
      res.sendError(res.SC_BAD_REQUEST, "Extra path info required");
    }
    // Cut off the leading "/" and append the query string
    // We"re assuming the path info URL is always absolute
    String url = site.substring(1) + (query == null ? "" : "?" + query);
    // Log the requested URL and redirect
    log(url); // or write to a special file
    res.sendRedirect(url);
  }
}





HttpServletResponse: setContentType( text/html; charset=UTF-8 );

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");
    }
  }
}





HttpServletResponse: setContentType("text/vnd.wap.wml")

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AreaCode extends HttpServlet {
  private Object[][] data = new Object[][] { { "Yukon Territory", new int[] { 867 } }, };
  Properties lookup = new Properties();
  public void init() {
    for (int i = 0; i < data.length; i++) {
      Object[] record = data[i];
      String state = (String) record[0];
      int[] codes = (int[]) record[1];
      for (int j = 0; j < codes.length; j++) {
        lookup.put(String.valueOf(codes[j]), state);
      }
    }
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/vnd.wap.wml");
    PrintWriter out = res.getWriter();
    String msg = null;
    String code = req.getParameter("code");
    String region = null;
    if (code != null) {
      region = lookup.getProperty(code);
    }
    out.println("<?xml version=\"1.0\"?>");
    out.println("<!DOCTYPE wml PUBLIC " + "\"-//WAPFORUM//DTD WML 1.1//EN\" "
        + "\"http://www.wapforum.org/DTD/wml_1.1.xml\">");
    out.println("<wml>");
    out.println("<card id=\"Code\" title=\"Code\">");
    out.println("  <p>");
    out.println("  Area code "" + code + ""<br/>");
    if (region != null) {
      out.println("  is " + region + ".<br/>");
    } else {
      out.println("  is not valid.<br/>");
    }
    out.println("  </p>");
    out.println("</card>");
    out.println("</wml>");
  }

}
/*
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC
  "-//WAPFORUM//DTD WML 1.1//EN"
  "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
  <card id="AreaCode" title="Enter an Area Code">
    <do type="accept" label="Enter">
      <go href="servlet/AreaCode?code=$(code)"/>
    </do>
    <p>
    Enter an Area Code: <input type="text" name="code"/>
    </p>
  </card>
</wml>
*/





HttpServletResponse: setHeader(String name, String value)

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloSpain extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    res.setHeader("Content-Language", "es");
    Locale locale = new Locale("es", "");
    DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
    fmt.setTimeZone(TimeZone.getDefault());
    out.println("En Espa\u00f1ol:");
    out.println("\u00a1Hola Mundo!");
    out.println(fmt.format(new Date()));
  }
}





HttpServletResponse: setHeader(String name, String value) (2)

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SiteSelector extends HttpServlet {
  Vector<String> sites = new Vector<String>();
  Random random = new Random();
  public void init() throws ServletException {
    sites.addElement("http://www.jexp.ru");
    sites.addElement("http://www.servlets.ru");
    sites.addElement("http://java.sun.ru/products/servlet");
    sites.addElement("http://www.google.ru");
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    int siteIndex = Math.abs(random.nextInt()) % sites.size();
    String site = sites.elementAt(siteIndex);
    res.setStatus(res.SC_MOVED_TEMPORARILY);
    res.setHeader("Location", site);
  }
}





HttpServletResponse: setStatus(int status)

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SiteSelector extends HttpServlet {
  Vector<String> sites = new Vector<String>();
  Random random = new Random();
  public void init() throws ServletException {
    sites.addElement("http://www.jexp.ru");
    sites.addElement("http://www.servlets.ru");
    sites.addElement("http://java.sun.ru/products/servlet");
    sites.addElement("http://www.google.ru");
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    int siteIndex = Math.abs(random.nextInt()) % sites.size();
    String site = sites.elementAt(siteIndex);
    res.setStatus(res.SC_MOVED_TEMPORARILY);
    res.setHeader("Location", site);
  }
}





ServletResponse: setBufferSize(int 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 Buffering extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setBufferSize(8 * 1024); // 8K 
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    int size = res.getBufferSize(); // returns 8096 or greater
    log("The default buffer size is " + size);
    out.println("The client won"t see this");
    res.reset();
    out.println("Nor will the client see this!");
    res.reset();
    out.println("And this won"t be seen if sendError() is called");
    if (req.getParameter("param") == null) {
      res.sendError(res.SC_BAD_REQUEST, "param needed");
    }
  }
}