概述
一 Request对象的继承体系结构
ServletRequest -- 接口
| 继承
HttpServletRequest -- 接口
| 实现
org.apache.catalina.connector.RequestFacade 类(tomcat)
1. 当我们写一个Servlet类实现Servlet接口时
package cn.itcast.web.servlet;
import javax.jws.WebService;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/servlet01")
public class ServletDemo01 implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
//提供服务的方法
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println(servletRequest);
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
注意service()方法中传递的参数类型是ServletRequest servletRequest。
当我们把这个对象打印出来时,发现Tomcat传递的实际参数类型是org.apache.catalina.connector.RequestFacade
2. 当我们写一个Servlet类继承GenericServlet类时
package cn.itcast.web.servlet;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/servlet02")
public class ServletDemo02 extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println(servletRequest);
}
}
注意service()方法中传递的参数类型是ServletRequest servletRequest。
当我们把这个对象打印出来时,发现Tomcat传递的实际参数类型是org.apache.catalina.connector.RequestFacade。
2. 当我们写一个Servlet类继承HttpServlet类时
package cn.itcast.web.servlet;
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("/servlet03")
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost方法...");
}
}
注意doGet()和doPost()方法中传递的参数类型是HttpServletRequest req。
当我们把这个对象打印出来时,发现Tomcat传递的实际参数类型是org.apache.catalina.connector.RequestFacade。
二 通过Request对象获取请求数据消息
1. 获取请求行数据
* GET /day14/demo1?name=zhangsan HTTP/1.1
* 方法:
1. 获取请求方式 :GET
* String getMethod()
2. (*)获取虚拟目录:/day14
* String getContextPath()
3. 获取Servlet路径: /demo1
* String getServletPath()
4. 获取get方式请求参数:name=zhangsan
* String getQueryString()
5. (*)获取请求URI:/day14/demo1
* String getRequestURI(): /day14/demo1
* StringBuffer getRequestURL() :http://localhost/day14/demo1
* URL:统一资源定位符 : http://localhost/day14/demo1 中华人民共和国
* URI:统一资源标识符 : /day14/demo1 共和国
6. 获取协议及版本:HTTP/1.1
* String getProtocol()
7. 获取客户机的IP地址:
* String getRemoteAddr()
案例:输入的网址是http://localhost:8080/day13_Servlet/requestDemo01?name=zhangsan
package cn.itcast.web.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;
/**
* 演示通过Request对象获取请求行数据
*/
@WebServlet("/requestDemo01")
public class RequestDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 获取请求方式
String method = req.getMethod();
System.out.println(method);//结果:GET
//2. (*)获取虚拟目录:/day14
String contextPath = req.getContextPath();
System.out.println(contextPath);//结果:/day13_Servlet
//3. 获取Servlet路径: /demo1
String servletPath = req.getServletPath();
System.out.println(servletPath);//结果:/requestDemo01
//4. 获取get方式请求参数
String queryString = req.getQueryString();
System.out.println(queryString);//结果:name=zhangsan
//5. (*)获取请求URI:/day14/demo1
String requestURI = req.getRequestURI();
System.out.println(requestURI);//结果:/day13_Servlet/requestDemo01
StringBuffer requestURL = req.getRequestURL();
System.out.println(requestURL);//结果:http://localhost:8080/day13_Servlet/requestDemo01
//6. 获取协议及版本:HTTP/1.1
String protocol = req.getProtocol();
System.out.println(protocol);//结果:HTTP/1.1
//7. 获取客户机的IP地址
String remoteAddr = req.getRemoteAddr();
System.out.println(remoteAddr);//结果:0:0:0:0:0:0:0:1,返回的是IPV6的地址
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
2. 获取请求头数据
* 方法:
* (*)String getHeader(String name):通过请求头的名称获取请求头的值
* Enumeration<String> getHeaderNames():获取所有的请求头名称
package cn.itcast.web.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;
/**
* 演示通过Request对象获取请求行数据
*/
@WebServlet("/requestDemo02")
public class RequestDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//通过请求头的名称获取请求头的值
String host = req.getHeader("Host");
System.out.println(host);//结果:localhost:8080
String userAgent = req.getHeader("User-Agent");
System.out.println(userAgent);//结果:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36
String accept = req.getHeader("Accept");//结果:
System.out.println(accept);//结果:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
String acceptLanguage = req.getHeader("Accept-Language");
System.out.println(acceptLanguage);//结果:zh-CN,zh;q=0.9
String acceptEncoding = req.getHeader("Accept-Encoding");
System.out.println(acceptEncoding);//结果:gzip, deflate, br
String referer = req.getHeader("Referer");
System.out.println(referer);//结果:null
String connection = req.getHeader("Connection");
System.out.println(connection);//结果:keep-alive
//获取所有的请求头名称
Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headName = headerNames.nextElement();
System.out.print(headName + ":");
System.out.println(req.getHeader(headName));
}
/**
结果:
host:localhost:8080
connection:keep-alive
upgrade-insecure-requests:1
user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36
accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,;q=0.8,application/signed-exchange;v=b3
sec-fetch-site:none
sec-fetch-mode:navigate
accept-encoding:gzip, deflate, br
accept-language:zh-CN,zh;q=0.9
cookie:JSESSIONID=CE853D0024D1E02C250D84171184B315; Idea-57b4784d=a9f88c09-1eab-4772-b057-6159cc7b8abf
**/
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
3. 获取请求体数据
* 请求体:只有POST请求方式,才有请求体,在请求体中封装了POST请求的请求参数
* 步骤:
1. 获取流对象
* BufferedReader getReader():获取字符输入流,只能操作字符数据
* ServletInputStream getInputStream():获取字节输入流,可以操作所有类型数据
* 在文件上传知识点后讲解
2. 再从流对象中拿数据
package cn.itcast.web.request;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
/**
* 演示通过Request对象获取请求行数据
*/
@WebServlet("/requestDemo03")
public class RequestDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//通过getReader方式获取请求体
BufferedReader reader = req.getReader();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);//结果:username=gao&password=123
}
}
}
4. 获取请求参数通用方式
不论get还是post请求方式都可以使用下列方法来获取请求参数
1. String getParameter(String name):根据参数名称获取参数值 username=zs&password=123
2. String[] getParameterValues(String name):根据参数名称获取参数值的数组 hobby=xx&hobby=game
3. Enumeration<String> getParameterNames():获取所有请求的参数名称
4. Map<String,String[]> getParameterMap():获取所有参数的map集合
* 中文乱码问题:
* get方式:tomcat 8 已经将get方式乱码问题解决了
* post方式:会乱码
* 解决:在获取参数前,设置request的编码request.setCharacterEncoding("utf-8");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<form action="/day13_Servlet/requestDemo04" method="post">
<input type="text" placeholder="请输入用户名..." name="username"><br/>
<input type="text" placeholder="请输入密码..." name="password"><br/>
爱好: 
游泳<input type="checkbox" name="hobby" value="swimming">
跑步<input type="checkbox" name="hobby" value="running"><br/>
<input type="submit" value="注册">
</form>
</body>
</html>
package cn.itcast.web.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.Arrays;
import java.util.Enumeration;
import java.util.Map;
/**
* 演示通过Request对象获取请求体数据
*/
@WebServlet("/requestDemo04")
public class RequestDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
System.out.println(username);
String password = req.getParameter("password");
System.out.println(password);
String[] hobby = req.getParameterValues("hobby");
System.out.println(Arrays.toString(hobby));
Enumeration<String> parameterNames = req.getParameterNames();
while(parameterNames.hasMoreElements()){
System.out.println(parameterNames.nextElement());
}
while(parameterNames.hasMoreElements()){
System.out.println(parameterNames.nextElement());
}
Map<String, String[]> parameterMap = req.getParameterMap();
for(Map.Entry<String,String[]> entry:parameterMap.entrySet()){
System.out.println(entry.getKey());
System.out.println(Arrays.toString(entry.getValue()));
}
}
}
5. 请求转发:一种在服务器内部的资源跳转方式
1. 步骤:
1. 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)
2. 使用RequestDispatcher对象来进行转发:forward(ServletRequest request, ServletResponse response)
2. 特点:
1. 浏览器地址栏路径不发生变化
2. 只能转发到当前服务器内部资源中
3. 即使转发,也只有一次请求,多个资源之间使用的是同一个请求
package cn.itcast.web.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;
/**
* 演示通过Request对象获取请求体数据
*/
@WebServlet("/requestDemo06")
public class RequestDemo06 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("requestDemo06被访问了");
// 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)
RequestDispatcher requestDispatcher = req.getRequestDispatcher("requestDemo07");
//使用RequestDispatcher对象来进行转发:forward(ServletRequest request, ServletResponse response)
requestDispatcher.forward(req,resp);
}
}
package cn.itcast.web.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;
/**
* 演示通过Request对象获取请求体数据
*/
@WebServlet("/requestDemo07")
public class RequestDemo07 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("requestDemo07被访问了");
}
}
结果是:requestDemo06和requestDemo07都被访问了。
6. Request共享数据
* 域对象:一个有作用范围的对象,可以在作用范围内共享数据
* request域:代表一次请求的范围,一般用于请求转发的多个资源中共享数据
* 共享数据的方法:
1. void setAttribute(String name,Object obj):存储数据
2. Object getAttitude(String name):通过键获取值
3. void removeAttribute(String name):通过键移除键值对
package cn.itcast.web.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;
/**
* 演示通过Request对象获取请求体数据
*/
@WebServlet("/requestDemo06")
public class RequestDemo06 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("requestDemo06被访问了");
//给request对象存储数据
req.setAttribute("name","zhangsan");
// 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)
RequestDispatcher requestDispatcher = req.getRequestDispatcher("requestDemo07");
//使用RequestDispatcher对象来进行转发:forward(ServletRequest request, ServletResponse response)
requestDispatcher.forward(req,resp);
}
}
package cn.itcast.web.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;
/**
* 演示通过Request对象获取请求体数据
*/
@WebServlet("/requestDemo07")
public class RequestDemo07 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("requestDemo07被访问了");
//通过request获取属性值
System.out.println(req.getAttribute("name"));//结果:"zhangsan"
}
}
7. 获取ServletContext
* ServletContext getServletContext()
package cn.itcast.web.request;
import javax.servlet.ServletContext;
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;
/**
* 演示通过Request对象获取servletContext
*/
@WebServlet("/requestDemo08")
public class RequestDemo08 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = req.getServletContext();
System.out.println(servletContext);
}
}
最后
以上就是高挑狗为你收集整理的Servlet之Request对象的全部内容,希望文章能够帮你解决Servlet之Request对象所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复