目 录
web 服务器接收到客户端的 http 请求,针对这个请求,分别创建一个代表请求的 HttpServletRequest 对象,代表响应的一个 HttpServletResponse 对象。
- 如果要获取客户端请求过来的参数:找 HttpServletRequest
- 如果要给客户端响应一些信息:找 HttpServletResponse
1. HttpServletResponse中的方法
1.1 负责向浏览器发送数据的方法
public ServletOutputStream getOutputStream() throws IOException;
public PrintWriter getWriter() throws IOException;
1.2 负责向浏览器发送响应头的常用方法
public void setCharacterEncoding(String charset);
public void setContentLength(int len);
public void setContentLengthLong(long len);
public void setContentType(String type);
public void setDateHeader(String name, long date);
public void addDateHeader(String name, long date);
public void setHeader(String name, String value);
public void addHeader(String name, String value);
public void setIntHeader(String name, int value);
public void addIntHeader(String name, int value);
1.3 响应状态码
public static final int SC_CONTINUE = 100;
public static final int SC_SWITCHING_PROTOCOLS = 101;
public static final int SC_OK = 200;
public static final int SC_CREATED = 201;
public static final int SC_ACCEPTED = 202;
public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
public static final int SC_NO_CONTENT = 204;
public static final int SC_RESET_CONTENT = 205;
public static final int SC_PARTIAL_CONTENT = 206;
public static final int SC_MULTIPLE_CHOICES = 300;
public static final int SC_MOVED_PERMANENTLY = 301;
public static final int SC_MOVED_TEMPORARILY = 302;
public static final int SC_FOUND = 302;
public static final int SC_SEE_OTHER = 303;
public static final int SC_NOT_MODIFIED = 304;
public static final int SC_USE_PROXY = 305;
public static final int SC_TEMPORARY_REDIRECT = 307;
public static final int SC_BAD_REQUEST = 400;
public static final int SC_UNAUTHORIZED = 401;
public static final int SC_PAYMENT_REQUIRED = 402;
public static final int SC_FORBIDDEN = 403;
public static final int SC_NOT_FOUND = 404;
public static final int SC_METHOD_NOT_ALLOWED = 405;
public static final int SC_NOT_ACCEPTABLE = 406;
public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
public static final int SC_REQUEST_TIMEOUT = 408;
public static final int SC_CONFLICT = 409;
public static final int SC_GONE = 410;
public static final int SC_LENGTH_REQUIRED = 411;
public static final int SC_PRECONDITION_FAILED = 412;
public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;
public static final int SC_REQUEST_URI_TOO_LONG = 414;
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
public static final int SC_EXPECTATION_FAILED = 417;
public static final int SC_INTERNAL_SERVER_ERROR = 500;
public static final int SC_NOT_IMPLEMENTED = 501;
public static final int SC_BAD_GATEWAY = 502;
public static final int SC_SERVICE_UNAVAILABLE = 503;
public static final int SC_GATEWAY_TIMEOUT = 504;
public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2. HttpServletResponse常见应用
- 向浏览器输出信息
- 下载文件
- 验证码实现
- 重定向
2.1 下载文件
步骤:
- 获取下载文件的路径
- 获取下载文件的名称
- 设置响应头信息,让浏览器能够支持下载我们需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileInputStream流写入到buffer缓冲区
- 使用OutputStream将缓冲区中的数据输出到客户端
(1)创建一个类,ResponseServlet.java,内容如下
package com.yuhuofei.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* @Description 下载文件
* @ClassName ResponseServlet
* @Author yuhuofei
* @Date 2022/5/15 23:29
* @Version 1.0
*/
public class ResponseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取要下载的文件的路径
String filePath = "D:\\IDEA\\person-project\\javaweb\\01-servlet\\src\\main\\resources\\Pod架构图.JPG";
//2、获取要下载的文件的名称
String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
//3、设置响应头,让浏览器能支持下载文件,并设置编码为UTF-8
resp.setHeader("Content-Disposition", "attachment; fileName="+ URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
//4、获取下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(filePath);
//5、创建缓冲区
byte[] buffer = new byte[1024];
int len;
//6、获取输出流对象
ServletOutputStream fileOutputStream = resp.getOutputStream();
//7、将fileInputStream写到buffer缓冲区
while ((len = fileInputStream.read(buffer))!=-1){
//8、使用fileOutputStream将缓冲区的数据输出到客户端
fileOutputStream.write(buffer,0,len);
}
//9、关闭流
fileInputStream.close();
fileOutputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(2)修改 web.xml,如下所示
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 注册servlet-->
<servlet>
<servlet-name>download</servlet-name>
<servlet-class>com.yuhuofei.servlet.ResponseServlet</servlet-class>
</servlet>
<!-- 配置servlet的请求路径-->
<servlet-mapping>
<servlet-name>download</servlet-name>
<url-pattern>/downloadFile</url-pattern>
</servlet-mapping>
</web-app>
(3)启动 tomcat 服务器,在浏览器中输入 http://localhost:8080/01-servlet/downloadFile ,然后回车
2.2 图形验证码功能
(1)新建一个 ImageServlet.java 类,内容如下
package com.yuhuofei.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* @Description 图形验证码功能
* @ClassName ImageServlet
* @Author yuhuofei
* @Date 2022/5/16 0:15
* @Version 1.0
*/
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置每3秒自动刷新一次
resp.setHeader("refresh", "3");
//在内存中创建一张图片
BufferedImage image = new BufferedImage(50, 20, BufferedImage.TYPE_INT_RGB);
//操作图片的类,可理解为画笔
Graphics2D graphics2D = (Graphics2D) image.getGraphics();
//给图片设置背景颜色,范围是(0,0)到(50,20)
graphics2D.setColor(Color.white);
graphics2D.fillRect(0, 0, 50, 20);
//给图片写数据
graphics2D.setColor(Color.RED);
graphics2D.setFont(new Font(null, Font.BOLD, 20));
graphics2D.drawString(getNum(), 2.5f, 20.0f);
//设置响应头,告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//设置不缓存
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Pragma", "no-cache");
resp.setDateHeader("expires", -1);
//把图片写给浏览器
ImageIO.write(image, "jpg", resp.getOutputStream());
}
//获取随机数
private String getNum() {
Random random = new Random();
//自动生成[0,9999)范围内的随机数
String num = random.nextInt(9999) + "";
StringBuilder stringBuilder = new StringBuilder();
//如果自动生成的随机数不足4位,自动补上0
for (int i = 0; i < 4 - num.length(); i++) {
stringBuilder.append("0");
}
num = stringBuilder.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(2)修改 web.xml 的内容,如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 注册servlet-->
<servlet>
<servlet-name>image</servlet-name>
<servlet-class>com.yuhuofei.servlet.ImageServlet</servlet-class>
</servlet>
<!-- 配置servlet的请求路径-->
<servlet-mapping>
<servlet-name>image</servlet-name>
<url-pattern>/getImage</url-pattern>
</servlet-mapping>
</web-app>
(3)启动 tomcat 服务器,请求 http://localhost:8080/01-servlet/getImage ,结果如下
2.3 实现重定向
常见的重定向应用场景是用户登录,下面示例演示重定向。
(1)新建一个 RedirectServlet.java 类,内容如下
package com.yuhuofei.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Description 验证重定向
* @ClassName ImageServlet
* @Author yuhuofei
* @Date 2022/5/16 23:41
* @Version 1.0
*/
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//重定向到图形验证码页面
resp.sendRedirect("/01-servlet/getImage");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(2)修改 web.xml 文件,如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 注册图形验证码的servlet-->
<servlet>
<servlet-name>image</servlet-name>
<servlet-class>com.yuhuofei.servlet.ImageServlet</servlet-class>
</servlet>
<!-- 配置图形验证码的请求路径-->
<servlet-mapping>
<servlet-name>image</servlet-name>
<url-pattern>/getImage</url-pattern>
</servlet-mapping>
<!-- 注册重定向的servlet-->
<servlet>
<servlet-name>redirect</servlet-name>
<servlet-class>com.yuhuofei.servlet.RedirectServlet</servlet-class>
</servlet>
<!-- 配置重定向的请求路径-->
<servlet-mapping>
<servlet-name>redirect</servlet-name>
<url-pattern>/redirect</url-pattern>
</servlet-mapping>
</web-app>
(3)启动 tomcat 服务器,在浏览器中输入 http://localhost:8080/01-servlet/redirect ,然后回车,结果如下,展示了图形验证码的页面,并且浏览器的地址栏也变为了 http://localhost:8080/01-servlet/getImage ,重定向成功。
重定向和转发的区别:
- 相同点:页面都会实现跳转
- 不同点:(1)转发,浏览器地址栏的 url 不会变化,状态码是 307 ,转发路径写 /资源名 就行(2)重定向,浏览器地址栏的 url 会变化,状态码是 302 ,重定向路径要写 /上下文/资源名
二者的原理示意图如下:
请求转发:A 请求 B ,B 将请求转发给 C 进行处理,C 处理完成后将结果返回给 B ,然后 B 再将结果返回给 A 。
请求重定向:A 请求 B ,B 直接返回且告诉 A 去请求 C ,让 C 进行处理,然后 A 请求 C 。
2.4 一个简单的登录重定向示例
(1)新建一个 LoginServlet.java 类,内容如下
package com.yuhuofei.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Description 登录接口
* @ClassName LoginServlet
* @Author yuhuofei
* @Date 2022/5/17 20:14
* @Version 1.0
*/
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("用户名是:" + username + "\n" + "密码是:" + password);
//重定向到登录成功页面
resp.sendRedirect("/01-servlet/LoginSuccess.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(2)修改 web.xml 文件,如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 注册登录的servlet-->
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.yuhuofei.servlet.LoginServlet</servlet-class>
</servlet>
<!-- 配置登录的请求路径-->
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
(3)修改 index.jsp 文件,如下
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>登录</h2>
<form action="${pageContext.request.contextPath}/login" method="get">
账号: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
(4)新增一个 LoginSuccess.jsp 文件,与 index.jsp 在同一个目录下
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录成功!</h1>
</body>
</html>
(5)启动 tomcat 服务器,浏览器会自动打开首页,然后输入账号密码进行登录,结果如下