HttpServlet(2):深入HttpServletResponse

54 阅读2分钟

深入HttpServletResponse

Response:响应。从客户端响应到浏览器

打开HttpServletResponse源代码,我们能看到

public interface HttpServletResponse extends ServletResponse{

}

里面有很多add,encode,send,set,get方法和状态码

image.png

核心响应控制方法

//设置 HTTP 响应状态码(如 200、404、500 等)。
public static final int SC_OK = 200;
public static final int SC_NOT_FOUND = 404;
public static final int SC_INTERNAL_SERVER_ERROR = 500;
public void setStatus(int sc);
//发送错误响应,并可附带错误信息。常用于处理异常或自定义错误页面。
public void sendError(int sc, String msg) throws IOException;
public void sendError(int sc) throws IOException;
//发送重定向指令,客户端会跳转到指定 URL。
public void sendRedirect(String location) throws IOException;
//设置响应头(Headers)
public void setHeader(String name, String value);

常见响应头:

content-type:text/html; charset=utf-8

connection:keep-alive

content-encoding:gzip

//向响应中添加一个 Cookie,用于在客户端存储数据。
public void addCookie(Cookie cookie);
//对 URL 进行编码,确保 Session ID 能正确传递(尤其在 URL 重写时)。
public String encodeURL(String url);

关于ServletResponse接口

public interface ServletResponse {

    
    public String getCharacterEncoding();

    public String getContentType();
    
    //获取一个 ServletOutputStream 对象,用于向客户端发送二进制数据。
    public ServletOutputStream getOutputStream() throws IOException;
    
    //获取一个 PrintWriter 对象,用于向客户端发送文本数据。
    public PrintWriter getWriter() throws IOException;
    
    //// 设置响应的字符编码(如 UTF-8)。
    public void setCharacterEncoding(String charset);

    //设置响应体的长度。
    public void setContentLength(int len);
    public void setContentLengthLong(long len);

    ////设置响应的内容类型(如 text/html, application/json 等)。
    public void setContentType(String type);

    //设置响应缓冲区的大小。
    public void setBufferSize(int size);

    public int getBufferSize();

    //刷新缓冲区,将所有剩余的数据发送到客户端。
    public void flushBuffer() throws IOException;

    //清空缓冲区中的内容,但不重置其他响应头或状态码。
    public void resetBuffer();

    //检查响应是否已经被提交给客户端。
    public boolean isCommitted();

    //清空缓冲区中的内容,并重置所有响应头和状态码。
    public void reset();

    public void setLocale(Locale loc);

    public Locale getLocale();
    
}

下面是一个简单的示例,展示如何使用这些常用方法:

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ServletResponseExample {
    public void handleResponse(HttpServletResponse response) throws IOException {
        // 设置响应内容类型和字符编码
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 获取PrintWriter对象,用于发送文本数据
        PrintWriter writer = response.getWriter();
        writer.println("{\"message\": \"Hello, World!\"}");

        // 设置响应体长度
        response.setContentLength(writer.toString().getBytes().length);

        // 刷新缓冲区,将数据发送给客户端
        writer.flush();

        // 检查响应是否已经提交
        if (!response.isCommitted()) {
            // 如果没有提交,可以进行其他操作
            response.resetBuffer();
        }
    }
}