Using HttpServletResponse: Methods, Examples, and Best Practices
This article explains the HttpServletResponse object's role in Java web development, details common response header methods, highlights differences between addXXX and setXXX, and provides four complete servlet code examples covering cache control, page refresh, file download (including Chinese filenames), and dynamic image generation.
HttpServletResponse is the object a servlet uses to send HTTP responses to the client. This article introduces the most frequently used methods such as addCookie , addHeader , addIntHeader , setStatus , setDateHeader , setHeader , and setIntHeader , and explains that addXXX adds a header while setXXX replaces an existing header.
Four practical examples are presented:
Case 1 – Disable browser caching using setHeader to set Expires , Cache-Control and a custom progam header.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Disable caching
resp.setHeader("Expires", "-1");
resp.setHeader("Cache-Control", "No-Cache");
resp.setHeader("progam", "No-Cache");
// Write response body
resp.getOutputStream().write("haha".getBytes());
}Case 2 – Automatic page refresh with two sub‑cases.
a) Refresh the current page every second:
// Define a counter
int count = 0;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Refresh every 1 second
resp.setIntHeader("Refresh", 1);
count++;
resp.getOutputStream().write((count + "").getBytes());
}b) Redirect to another page after three seconds:
// Redirect after 3 seconds
resp.setHeader("Refresh", "3;url=/myDay06/NoCacheResponse");
resp.getOutputStream().write("刷新".getBytes());Case 3 – File download (both non‑Chinese and Chinese filenames).
a) Non‑Chinese filename download:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = getServletContext();
String path = context.getRealPath("/1.jpg");
resp.setHeader("Content-Disposition", "attachment;filename=1.jpg");
resp.setHeader("Content-type", "application/octet-stream");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
BufferedOutputStream out = new BufferedOutputStream(resp.getOutputStream());
byte[] buff = new byte[1024];
int len = 0;
while ((len = bis.read(buff)) != -1) {
out.write(buff, 0, len);
out.flush();
}
out.close();
bis.close();
}b) Chinese filename download (uses URLEncoder ):
public class FileChineseDownload extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = getServletContext();
String path = context.getRealPath("/美女.jpg");
String filename = path.substring(path.lastIndexOf("\\") + 1);
resp.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
resp.setHeader("Content-Type", "application/octet-Stream");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
BufferedOutputStream out = new BufferedOutputStream(resp.getOutputStream());
byte[] buff = new byte[1024];
int len = 0;
while ((len = bis.read(buff)) != -1) {
out.write(buff, 0, len);
out.flush();
}
bis.close();
out.close();
}
}Case 4 – Dynamic verification image generation using BufferedImage , Graphics , and ImageIO to draw a captcha.
public class ActionImage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int width = 200;
int height = 50;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics gra = image.getGraphics();
// Draw blue rectangle
gra.setColor(Color.BLUE);
gra.drawRect(0, 0, width, height);
// Fill yellow background
gra.setColor(Color.YELLOW);
gra.fillRect(0, 0, width - 1, height - 1);
// Draw interference lines
Random rLine = new Random();
gra.setColor(Color.BLACK);
for (int x = 0; x < 10; x++) {
gra.drawLine(rLine.nextInt(width), rLine.nextInt(height), rLine.nextInt(width), rLine.nextInt(height));
}
// Draw random digits in red, bold italic font
gra.setColor(Color.RED);
gra.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 23));
Random rNumber = new Random();
int x = 23;
for (int i = 0; i < 4; i++) {
gra.drawString(rNumber.nextInt(10) + "", x, 30);
x += 40;
}
// Output image as JPEG
ImageIO.write(image, "jpg", resp.getOutputStream());
}
}Important notes: a servlet must not mix character and byte streams; data written via streams is first stored in the response buffer and then sent according to the HTTP protocol; the container automatically closes streams after the response is committed.
IT Xianyu
We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.