HttpServletResponse相应结果
时间: 2023-08-11 08:32:29 浏览: 38
HttpServletResponse 可以用来响应 HTTP 请求,返回客户端需要的结果。常见的响应结果有:
1. 设置响应状态码:
```java
response.setStatus(HttpServletResponse.SC_OK); // 设置响应状态码为200
```
2. 设置响应头:
```java
response.setHeader("Content-Type", "text/html;charset=UTF-8"); // 设置响应头
```
3. 获取输出流对象并写入响应数据:
```java
PrintWriter out = response.getWriter();
out.write("Hello, World!"); // 将数据写入输出流中
out.close(); // 关闭输出流
```
完整示例代码:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setStatus(HttpServletResponse.SC_OK); // 设置响应状态码为200
response.setHeader("Content-Type", "text/html;charset=UTF-8"); // 设置响应头
PrintWriter out = response.getWriter();
out.write("Hello, World!"); // 将数据写入输出流中
out.close(); // 关闭输出流
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)