响应

HttpServletResponse

public interface HttpServletResponse extends ServletResponse {
    int SC_CONTINUE = 100;
    int SC_SWITCHING_PROTOCOLS = 101;
    int SC_OK = 200;
    int SC_CREATED = 201;
    int SC_ACCEPTED = 202;
    int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    int SC_NO_CONTENT = 204;
    int SC_RESET_CONTENT = 205;
    int SC_PARTIAL_CONTENT = 206;
    int SC_MULTIPLE_CHOICES = 300;
    int SC_MOVED_PERMANENTLY = 301;
    int SC_MOVED_TEMPORARILY = 302;
    int SC_FOUND = 302;
    int SC_SEE_OTHER = 303;
    int SC_NOT_MODIFIED = 304;
    int SC_USE_PROXY = 305;
    int SC_TEMPORARY_REDIRECT = 307;
    int SC_BAD_REQUEST = 400;
    int SC_UNAUTHORIZED = 401;
    int SC_PAYMENT_REQUIRED = 402;
    int SC_FORBIDDEN = 403;
    int SC_NOT_FOUND = 404;
    int SC_METHOD_NOT_ALLOWED = 405;
    int SC_NOT_ACCEPTABLE = 406;
    int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    int SC_REQUEST_TIMEOUT = 408;
    int SC_CONFLICT = 409;
    int SC_GONE = 410;
    int SC_LENGTH_REQUIRED = 411;
    int SC_PRECONDITION_FAILED = 412;
    int SC_REQUEST_ENTITY_TOO_LARGE = 413;
    int SC_REQUEST_URI_TOO_LONG = 414;
    int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    int SC_EXPECTATION_FAILED = 417;
    int SC_INTERNAL_SERVER_ERROR = 500;
    int SC_NOT_IMPLEMENTED = 501;
    int SC_BAD_GATEWAY = 502;
    int SC_SERVICE_UNAVAILABLE = 503;
    int SC_GATEWAY_TIMEOUT = 504;
    int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

    void addCookie(Cookie var1);

    boolean containsHeader(String var1);

    String encodeURL(String var1);

    String encodeRedirectURL(String var1);

    /** @deprecated */
    String encodeUrl(String var1);

    /** @deprecated */
    String encodeRedirectUrl(String var1);

    void sendError(int var1, String var2) throws IOException;

    void sendError(int var1) throws IOException;

    void sendRedirect(String var1) throws IOException;

    void setDateHeader(String var1, long var2);

    void addDateHeader(String var1, long var2);

    void setHeader(String var1, String var2);

    void addHeader(String var1, String var2);

    void setIntHeader(String var1, int var2);

    void addIntHeader(String var1, int var2);

    void setStatus(int var1);

    /** @deprecated */
    void setStatus(int var1, String var2);

    int getStatus();

    String getHeader(String var1);

    Collection getHeaders(String var1);

    Collection getHeaderNames();
}
可以使用HttpServletResponse来对浏览器进行响应,常见的操作如下:

1. 使用resp.setContentType()设置响应类型
2. 使用resp.getWriter()获取PrintWriter对象,来对页面打印信息
3. 使用resp.setHeader()、addHeader()等方法设置响应头信息
4. 使用resp.sendRedirect()、sendError()方法要求客户端重定向页面,或传输错误状态信息
5. 使用resp.getOutputStream()取得ServletOutputStream对象,对浏览器进行字节数据响应

设置响应头、缓冲区

/**
 * 处理响应头信息的Servlet
 */
public class ResponseHeaderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应头Content-Language来设置编码格式,
        // 相当于response.setCharacterEncoding()或response.setContentType()
        // 当通过setCharacterEncoding()或setContentType()设置了编码格式后,则会忽略setLocale()方法
        response.setLocale(Locale.CHINA);

        // 为某个头部信息设置值
        response.setHeader("Set-Cookie", "username=niezhicisgod; age=23; ");

        // 为某个头部信息添加值
        response.addHeader("Allow", "POST");

        // 如果头部的值为整数类型
        response.setIntHeader("Age", 233);

        response.addIntHeader("Retry-After", 233);

        // 如果头部的值为日期类型
        response.setDateHeader("Date", 233L);

        response.addDateHeader("Last-Modified", 233L);

        // 所有响应头的设置或添加,都必须在响应确认之前,否则都会被忽略;通过isConmmitted()判断响应是否确认
        boolean flag = response.isCommitted();

        PrintWriter out = response.getWriter();
        for (String head : response.getHeaderNames()) {
            out.print(head + ":" + response.getHeader(head));
        }

        // 清除所有对响应头的设置
        response.reset();
    }
}
/**
 * 对响应进行缓冲操作的Servlet
 */
public class ResponseBufferServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应的缓冲区大小,
        // 必须在response.getWriter()或response.getOutputStream()方法之前设置,
        // 否则会抛出IllegalStateException
        response.setBufferSize(233);

        // 将缓冲区中的信息发送给浏览器,然后清空缓冲区
        response.flushBuffer();

        //清除所有缓冲
        response.resetBuffer();
    }
}

response.setContentType()

因为浏览器需要知道如何处理你的响应,所以必须告知内容类型,setContentType()方法在响应头中设置content-type的值,只要指定MIME类型就可以了。由于编码设置与内容类型通常都要设置,所以调用setContentType()设置类型时,同时指定charset属性是个方便且常见的做法。
常见的MIME类型有:text/html、application/pdf、application/jar、application/x-zip、image/jpeg等
可以在web部署描述文件中定义MIME的类型映射:


    
    pdf
    
    application/pdf

在Servlet中可以使用ServletContext中的getMimeType()方法获取到文件的MIME类型

response.getOutputStream()输出字节流

通过getWriter()对浏览器进行字符输出,但也有时候需要直接对浏览器进行字节输出,此时可以通过response.getOutputStream()获取ServletOutputStream对象
/**
 * 下载文件的Servlet
 */
@WebServlet(name = "DownloadServlet", urlPatterns = "/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/pdf");

        // 声明不直接在浏览器中打开/下载,让用户自定义下载文件的目录
        response.setHeader("Content-Disposition", "attachment; filename=" + "dsaj.pdf");

        //ServletContext对象就代表着当前整个web应用程序
        InputStream in = getServletContext().getResourceAsStream("/WEB-INF/pdf/dsaj.pdf");
        ServletOutputStream out = response.getOutputStream();
        writeTo(in, out);
    }

    private void writeTo(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int length = -1;
        while((length = in.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.close();
    }
}

response.sendRedirect()、response.sendError()
之前的forward()方法都是在同一个请求中,所以request.setAttribute()设置属性对象,都可以在转发过程中共享
而response.sendRedirect()是要求浏览器重新请求另一个的URL,又称为重定向,这个方法会在响应中设置HTTP状态码301以及Location头(就是需要跳转的URL),浏览器会使用GET方式请求指定的URL,因此浏览器地址栏会发现URL的变更
/**
 * 演示重定向的Servlet
 */
@WebServlet(name = "RedirectServlet", urlPatterns = "/redirectServlet")
public class RedirectServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 重定向到下载的Servlet
        response.sendRedirect("/downloadServlet");
    }
}
如果在处理请求的过程中发生一些异常,可以使用response.sendError()方法,返回错误信息给浏览器;HttpServlet中的doGet()方法就默认使用了sendError()方法:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String protocol = req.getProtocol();
    String msg = lStrings.getString("http.method_get_not_supported");
    if(protocol.endsWith("1.1")) {
        resp.sendError(405, msg);    } else {
        resp.sendError(400, msg);
    }

}

你可能感兴趣的:(响应)