Java Tutorial/Servlet/Response

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

Get Servlet OutputStream from Servlet Response

   <source lang="java">

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet {

 public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOException
 {
   ServletOutputStream out = res.getOutputStream();
   res.setContentType("text/html");
   out.println("<html><head><title>Basic Servlet</title></head>");
   out.println("<body>Hello World</body></html>");
 }

}</source>





HTTP Response

   <source lang="java">

//Revised from jcommon web;

import java.io.*; import java.net.*; import java.util.*;

public class HTTPResponse {

 public static final HashMap<String,String> MIME_TYPES = new HashMap<String,String>();
 static {
   MIME_TYPES.put("gif", "image/gif");
   MIME_TYPES.put("jpeg", "image/jpeg");
   MIME_TYPES.put("jpg", "image/jpeg");
   MIME_TYPES.put("jpe", "image/jpeg");
   MIME_TYPES.put("bmp", "image/bmp");
   MIME_TYPES.put("png", "image/png");
   MIME_TYPES.put("tif", "image/tiff");
   MIME_TYPES.put("tiff", "image/tiff");
   MIME_TYPES.put("jnlp", "application/x-java-jnlp-file");
   MIME_TYPES.put("js", "application/x-javascript");
   MIME_TYPES.put("doc", "application/msword");
   MIME_TYPES.put("bin", "application/octet-stream");
   MIME_TYPES.put("exe", "application/octet-stream");
   MIME_TYPES.put("pdf", "application/pdf");
   MIME_TYPES.put("ai", "application/postscript");
   MIME_TYPES.put("eps", "application/postscript");
   MIME_TYPES.put("ps", "application/postscript");
   MIME_TYPES.put("rtf", "application/rtf");
   MIME_TYPES.put("class", "application/x-java-vm");
   MIME_TYPES.put("ser", "application/x-java-serialized-object");
   MIME_TYPES.put("jar", "application/x-java-archive");
   MIME_TYPES.put("sh", "application/x-sh");
   MIME_TYPES.put("tar", "application/x-tar");
   MIME_TYPES.put("zip", "application/zip");
   MIME_TYPES.put("ua", "audio/basic");
   MIME_TYPES.put("wav", "audio/x-wav");
   MIME_TYPES.put("mid", "audio/x-midi");
   MIME_TYPES.put("htm", "text/html");
   MIME_TYPES.put("html", "text/html");
   MIME_TYPES.put("css", "text/css");
   MIME_TYPES.put("txt", "text/plain");
   MIME_TYPES.put("mpeg", "video/mpeg");
   MIME_TYPES.put("mpg", "video/mpeg");
   MIME_TYPES.put("mpe", "video/mpeg");
   MIME_TYPES.put("qt", "video/quicktime");
   MIME_TYPES.put("mov", "video/quicktime");
   MIME_TYPES.put("avi", "video/avi");
   MIME_TYPES.put("movie", "video/x-sgi-movie");
 }
 
 public static String SERVER = "JavaWebServer/1.0";
 
 public static final int OK = 200;
 
 private Socket s;
 private int mode;
 private HashMap<String,String> headers;
 private HashSet<String> keys;
 
 public HTTPResponse(Socket s, int mode) throws IOException {
   this.s = s;
   this.mode = mode;
   
   headers = new HashMap<String,String>();
   keys = new HashSet<String>();
 }
 
 public void addHeader(String header, String value) {
   keys.add(header.toLowerCase());
   headers.put(header, value);
 }
 
 private void writeHeaders() throws IOException {
   if (mode == OK) {
     writeLine("HTTP/1.1 200 OK");
   }
   if (!keys.contains("server")) {
     headers.put("Server", SERVER);
   }
   if (!keys.contains("date")) {
     headers.put("Date", String.format("%EEE%, %d% %MMM% %yyyy% %HH%:%mm%:%ss% %Z%",new GregorianCalendar()));
   }
   
   Iterator<String> iterator = headers.keySet().iterator();
   String key;
   String value;
   while (iterator.hasNext()) {
     key = iterator.next();
     value = headers.get(key);
     writeLine(key + ": " + value);
   }
   
   writeLine("");
 }
 
 private void writeLine(String string) throws IOException {
   s.getOutputStream().write((string + "\r\n").getBytes());
 }
 
 public void writeFile(File f) throws IOException {
   if ((!keys.contains("content-type")) && (f.getName().indexOf(".") > -1)) {
     String ext = f.getName().substring(f.getName().lastIndexOf(".") + 1).toLowerCase();
     if (MIME_TYPES.containsKey(ext)) {
       headers.put("Content-Type", MIME_TYPES.get(ext));
     }
   }
   if (!keys.contains("content-length")) {
     headers.put("Content-Length", String.valueOf(f.length()));
   }
   writeHeaders();
   
   FileInputStream fis = new FileInputStream(f);
   byte[] b = new byte[512];
   int len;
   while ((len = fis.read(b)) > -1) {
     s.getOutputStream().write(b, 0, len);
   }
   s.getOutputStream().flush();
   s.close();
 }

}</source>





Servlet OutputStream

   <source lang="java">

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; public class MyServlet extends HttpServlet {

 public void doGet(HttpServletRequest req, HttpServletResponse res)
                              throws ServletException, IOException {
   ServletOutputStream out = res.getOutputStream();
   res.setContentType("text/plain"); 
   String file = req.getPathInfo();
   if (file == null) {
     out.println("Extra path info was null; should be a resource to view");
     return;
   }
   URL url = getServletContext().getResource(file);
   if (url == null) {
     out.println("Resource " + file + " not found");
     return;
   }
   URLConnection con = null;
   try {
     con = url.openConnection();
     con.connect();
   }
   catch (IOException e) {
     out.println("Resource " + file + " could not be read: " + e.getMessage());
     return;
   }
 }

}</source>





Servlet Response Send Error

   <source lang="java">

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; public class MyServlet extends HttpServlet {

 public void doGet(HttpServletRequest req, HttpServletResponse res)
                              throws ServletException, IOException {
   res.setBufferSize(8 * 1024); // 8K buffer
   res.setContentType("text/html");
   PrintWriter out = res.getWriter();
   int size = res.getBufferSize(); // returns 8096 or greater
   // Record the default size, in the log
   log("The default buffer size is " + size);
   out.println("The client won"t see this");
   res.reset();
   out.println("And this won"t be seen if sendError() is called");
   if (req.getParameter("important_parameter") == null) {
     res.sendError(res.SC_BAD_REQUEST, "important_parameter needed");
   }
 }

}</source>





Servlet Response Send Redirect

   <source lang="java">

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
       
      //redirect the user depending on the value of the "go" param
       String destination = getInitParameter("go");
       String contextPath = request.getContextPath();
       
        if(destination == null || destination.equals(""))
           throw new ServletException(
            "Missing or invalid "go" parameter in " +
              getClass().getName());
       
       if(destination.equals("weather"))
       //ensure URL rewriting
           response.sendRedirect(response.encodeRedirectURL(contextPath + "/weather") );
       
        if(destination.equals("maps"))
       //ensure URL rewriting
           response.sendRedirect(response.encodeRedirectURL(contextPath + "/maps") );
   }

}</source>