Request请求和Response响应


​2.1 重定向​​​​2.2 服务器输出字符数据到浏览器​​​​2.3 服务器输出字节数据到浏览器​​​​2.4 验证码​


1 Request请求

1.1 Request请求行数据

package Request;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
* Request请求行数据
*/
@WebServlet("/RequestServlet")
public class RequestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Request获取请求方式
String method = request.getMethod();
System.out.println(method);
// Request获取虚拟目录
String contextPath = request.getContextPath();
System.out.println(contextPath);
// 获取servlet路径
String servletPath = request.getServletPath();
System.out.println(servletPath);
// 获取get请求方式的请求参数
String name = request.getQueryString();
System.out.println(name);
// 获取请求方法的URI URL
String requestURI = request.getRequestURI();
System.out.println(requestURI);
StringBuffer requestURL = request.getRequestURL();
System.out.println(requestURL);
// 获取协议及版本
String protocol = request.getProtocol();
System.out.println(protocol);
// 获取客户机的IP
String remoteAddr = request.getRemoteAddr();
System.out.println(remoteAddr);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

Request请求和Response响应_java

1.2 Request获取请求头数据

package Request;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Enumeration;

/**
* Request获取请求头数据
*/
@WebServlet("/RequestServlet_02")
public class RequestServlet_02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取所有请求头名称
Enumeration<String> headerNames = request.getHeaderNames();
// 遍历
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
// 根据名称获取请求头的值
String value = request.getHeader(name);
System.out.println(name + "=" + value);
}
System.out.println("===================================================");
//案例: 演示获取请求头数据:user-agent
String agent = request.getHeader("user-agent");
// 判断agent的浏览器版本
if (agent.contains("Chrome")) {
System.out.println("我是谷歌浏览器");
} else if (agent.contains("Firefox")) {
System.out.println("我是火狐浏览器");
}
System.out.println("===================================================");
//案例: 演示获取请求头数据:referer
String referer = request.getHeader("referer");
System.out.println(referer);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

Request请求和Response响应_request_02

1.3 Request获取请求体数据

仅有post请求才能获取到请求体数据,在项目的web目录下建立一个regist.html文件:

Request请求和Response响应_request_03

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
</head>
<body>
<form action="http://localhost:8080/HttpServlet_war_exploded//RequestServlet_03" method="post">
<input type="text" name="username" placeholder="请输入用户名"><br>
<input type="text" name="password" placeholder="请输入密码"><br>
<input type="submit" value="注册">
</form>
</body>
</html>

在项目的src下建立一个RequestServlet_03文件:

package Request;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;

/**
* 获取请求消息体
*/
@WebServlet("/RequestServlet_03")
public class RequestServlet_03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求消息体,请求参数
// 获取字符流
BufferedReader reader = request.getReader();
// 读取数据
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}

启动服务器,访问regist.html文件,填写用户名和密码参数进行提交,可以在IDEA控制台获取到该表单提交的参数信息。

Request请求和Response响应_服务器_04

Request请求和Response响应_服务器_05

1.4 获取请求参数通用方式

在JavaEE项目的web目录下创建regist2.html文件:

Request请求和Response响应_http_06

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
</head>
<body>
<form action="http://localhost:8080/HttpServlet_war_exploded//RequestServlet_04" method="post">
<input type="text" name="username" placeholder="请输入用户名"><br>
<input type="text" name="password" placeholder="请输入密码"><br>
<input type="checkbox" name="hobby" value="game">游戏
<input type="checkbox" name="hobby" value="play">玩耍
<input type="checkbox" name="hobby" value="study">学习
<br>
<input type="submit" value="注册">
</form>
</body>
</html>

创建RequestServlet_04类:

package Request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

/**
* 获取请求消息体
*/
@WebServlet("/RequestServlet_04")
public class RequestServlet_04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get获取请求参数
// 1 根据参数名称获取参数值
String parameter = request.getParameter("username");
System.out.println("get");
System.out.println(parameter);
System.out.println("-------------------------------------------");
// 2 根据参数名称获取参数值的数组
String[] hobbies = request.getParameterValues("hobby");
for (String hobby : hobbies
) {
System.out.println(hobby);
}
System.out.println("-------------------------------------------");
// 3 获取所有请求的参数名称
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String name = parameterNames.nextElement();
System.out.println(name);
String value = request.getParameter(name);
System.out.println(value);
System.out.println("=====================");
}
System.out.println("-------------------------------------------");
// 4 获取所有参数的map集合
Map<String, String[]> parameterMap = request.getParameterMap();
// 遍历
Set<String> keySet = parameterMap.keySet();
for (String name : keySet
) {
// 获取键获取值
String[] values = parameterMap.get(name);
System.out.println(name);
for (String value : values
) {
System.out.println(value);
}
System.out.println("=====================");
}
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//post获取请求参数
//根据参数名称获取参数值
// System.out.println("post");
// String parameter = request.getParameter("username");
// System.out.println(parameter);
this.doGet(request, response);
}
}

启动服务器,访问regist2.html文件,输入参数进行提交:

Request请求和Response响应_request_07

Request请求和Response响应_request_08

get请求不会乱码,post请求乱码解决

在执行请求时执行流的编码:

request.setCharacterEncoding("utf-8");

1.5 请求转发(服务器内部的资源跳转方式)

创建两个Java文件:RequestServlet_05、RequestServlet_06,通过访问RequestServlet_05后,跳继续访问到RequestServlet_06。

package Request;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/RequestServlet_05")
public class RequestServlet_05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
System.out.println("RequestServlet_05被访问了......");
// 请求转发
// RequestDispatcher requestDispatcher = request.getRequestDispatcher("/RequestServlet_06");
// requestDispatcher.forward(request,response);
request.getRequestDispatcher("/RequestServlet_06").forward(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
package Request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/RequestServlet_06")
public class RequestServlet_06 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
System.out.println("RequestServlet_06被访问了......");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

Request请求和Response响应_java_09


特点:
1、浏览器地址不发生变化
2、只能发到当前服务器内部资源
3、转发是一次请求


1.6 共享数据

借助上面发的两个例子:在RequestServlet_05中定义一个name变量,值设为beijing,转发后在RequestServlet_06中可以获取到这个数据。

package Request;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/RequestServlet_05")
public class RequestServlet_05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");

//转发前存储数据到request域中
request.setAttribute("name","beijing");


System.out.println("RequestServlet_05被访问了......");
// 请求转发
// RequestDispatcher requestDispatcher = request.getRequestDispatcher("/RequestServlet_06");
// requestDispatcher.forward(request,response);
request.getRequestDispatcher("/RequestServlet_06").forward(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
package Request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/RequestServlet_06")
public class RequestServlet_06 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
System.out.println("RequestServlet_06被访问了......");

//转发后获取共享数据
Object name = request.getAttribute("name");
System.out.println(name);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

Request请求和Response响应_request_10

2 Response响应

2.1 重定向

Request请求和Response响应_服务器_11

package Response;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
* 重定向
*/
@WebServlet("/ResponseServlet_01")
public class ResponseServlet_01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("ResponseServlet_01...");
//重定向,当访问ResponseServlet_01时,自动跳转到ResponseServlet_02资源
// // 1 设置状态码为302
// response.setStatus(302);
// // 2 设置响应头location
// response.setHeader("location","ResponseServlet_02");

//重定向的简化写法
response.sendRedirect("ResponseServlet_02");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
package Response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/ResponseServlet_02")
public class ResponseServlet_02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("ResponseServlet_02...");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}


重定向特点:
1、地址发生变化
2、可以访问其他站点资源
3、重定向是两次请求,不能共享数据


2.2 服务器输出字符数据到浏览器

服务器传送数据至浏览器中文乱码解决:

//        获取流对象之前设置编码方式,告诉浏览器,服务器发送的消息体数据的编码
response.setContentType("text/html;charset=utf-8");
package Response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ResponseServlet_03")
public class ResponseServlet_03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取流对象之前设置编码方式,告诉浏览器,服务器发送的消息体数据的编码
response.setContentType("text/html;charset=utf-8");

//获取字符输出流
PrintWriter pw = response.getWriter();
//输出数据
pw.write("hello(你好) , response");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

2.3 服务器输出字节数据到浏览器

package Response;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/ResponseServlet_04")
public class ResponseServlet_04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取流对象之前设置编码方式,告诉浏览器,服务器发送的消息体数据的编码
response.setContentType("text/html;charset=utf-8");

//获取字节输出流
ServletOutputStream outputStream = response.getOutputStream();
//输出数据
outputStream.write("你好".getBytes(StandardCharsets.UTF_8));
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

2.4 验证码

写一个regist.html文件,模拟简单登录页面,使用标签插入服务器中的图片验证码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<script>
window.onload = function () {
//获取图片对象
var img = document.getElementById("check");
//绑定单击事件
img.onclick = function () {
//加时间戳
var date = new Date().getTime();
img.src = "/HttpServlet_war_exploded/ResponseServlet_05?" + date;
}

//获取文字对象
var text = document.getElementById("change");
//绑定单击事件
text.onclick = function () {
//加时间戳
var date = new Date().getTime();
img.src = "/HttpServlet_war_exploded/ResponseServlet_05?" + date;
}
}
</script>
</head>
<body>
<form action="http://localhost:8080/HttpServlet_war_exploded//RequestServlet_03" method="post">
<input type="text" name="username" placeholder="请输入用户名"><br>
<input type="text" name="password" placeholder="请输入密码"><br>
<img id="check" src="/HttpServlet_war_exploded/ResponseServlet_05"/>
<br>
<a id="change" href="#">看不清,换一张</a>
<input type="submit" value="注册">
</form>
</body>
</html>
package Response;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
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;

@WebServlet("/ResponseServlet_05")
public class ResponseServlet_05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//1.创建一对象,在内存中图片(验证码图片对象)
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.美化图片
//2.1 填充背景色
Graphics graphics = bufferedImage.getGraphics();//画笔对象
graphics.setColor(Color.PINK);
graphics.fillRect(0, 0, width, height);
//2.2 画边框
graphics.setColor(Color.BLUE);
graphics.drawRect(0, 0, width - 1, height - 1);
//2.3写验证码
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxqz0123456789";
//生成随机角标
Random random = new Random();
for (int i = 0; i <= 4; i++) {
int index = random.nextInt(str.length());
//获取字符
char c = str.charAt(index);
//2.3 写验证码
graphics.drawString(c + "", width / 5 * i, height / 2);
}
//2.4画干扰线
graphics.setColor(Color.GREEN);
//随机生成坐标点
for (int i = 0; i < 10; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1, y1, x2, y2);
}
//3.将图片输出到页面展示
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

Request请求和Response响应_response_12

3 ServletContext对象

Request请求和Response响应_服务器_13

package ServletContext;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "ServletContext_01", value = "/ServletContext_01")
public class ServletContext_01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取ServletContext对象
//获取方式1
// ServletContext servletContext1 = request.getServletContext();
//获取方式2
ServletContext servletContext2 = this.getServletContext();

// 定义一个文件名称
String filename = "beijing.html";
// 1 获取MIME类型
String mimeType = servletContext2.getMimeType(filename);
System.out.println(mimeType); //text/html

// 2 获取文件服务器路径
// 分别获取web目录下,web目录下的WEB-INF目录下,以及src目录下的文件地址
String realPath = servletContext2.getRealPath("/b.txt");//获取web目录
String realPath1 = servletContext2.getRealPath("/WEB-INF/c.txt");//web目录下的WEB-INF目录下
String realPath2 = servletContext2.getRealPath("/WEB-INF/classes/a.txt");//src目录下的文件地址
System.out.println(realPath);
System.out.println(realPath1);
System.out.println(realPath2);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

Request请求和Response响应_response_14