Table of contents
2. Request to get request data
1. Response setting response data function
4. Response response character data
5. Response response byte data
I. Overview
Request is the request object, Response is the response object
request: Get request data
The browser will send HTTP requests to the background server [Tomcat]
The HTTP request will contain a lot of request data [request line + request header + request body] The
background server [Tomcat] will analyze the data in the HTTP request and store the analysis results in an object. The stored object is the
request object, so we can obtain the relevant parameters of the request from the request object.
After obtaining the data, we can continue the subsequent business, such as obtaining the user name and password to realize the related business of the login operation
response: Set the response data.
After the business is processed, the background needs to return the result of the business processing to the front end, that is, the response data.
Encapsulate the response data into the response object.
The background server [Tomcat] will parse the response object, and stitch the results according to the format of [response line + response header + response body]. The browser
finally parses the result and displays the content in the browser for users to browse
Second, the Request object
1. Request inheritance system
The inheritance system of Request is ServletRequest-->HttpServletRequest-->RequestFacade
Tomcat needs to parse the request data, encapsulate it as a request object, and create a request object to pass to the service method
2. Request to get request data
The HTTP request data is divided into three parts in total, namely the request line, request header, and request body
①Get request line data
The request line contains three pieces of content, which are request method, request resource path, HTTP protocol and version
Get request method: GET
String getMethod()
Get the virtual directory (project access path): /request-demo
String getContextPath()
Get URL (Uniform Resource Locator): http://localhost:8080/request-demo/req1
StringBuffer getRequestURL()
Get URI (Uniform Resource Identifier): /request-demo/req1
String getRequestURI()
Get request parameters (GET method): username=zhangsan&password=123
String getQueryString()
② Get request header data
String getHeader(String name)
③ Get request body data
When the browser sends a GET request, there is no request body, so the request method needs to be changed to POST
Get the byte input stream. If the front end sends byte data, such as file data, use this method
ServletInputStream getInputStream()
Get the character input stream, if the front end sends plain text data, use this method
BufferedReader getReader()
④Get request parameters
Request parameters are part of the request data
If it is a GET request, the request parameters are in the request line
If it is a POST request, the request parameters are generally in the request body
GET method
String getQueryString()
POST method
BufferedReader getReader();
Unified way to obtain GET and POST request parameters
method one:
//示例,直接使用POST调用GET方法,提高代码复用率
@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求方式
String method = req.getMethod();
//获取请求参数
String params = "";
if("GET".equals(method)){
params = req.getQueryString();
}else if("POST".equals(method)){
BufferedReader reader = req.getReader();
params = reader.readLine();
}
//将请求参数进行打印控制台
System.out.println(params);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
Method Two:
Get all parameter Map collections
Map<String,String[]> getParameterMap()
Get parameter value by name
String[] getParameterValues(String name)
Get parameter value by name (single value)
String getParameter(String name)
@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//GET请求逻辑
System.out.println("get....");
//1. 获取所有参数的Map集合
Map<String, String[]> map = req.getParameterMap();
for (String key : map.keySet()) {
// username:zhangsan lisi
System.out.print(key+":");
//获取值
String[] values = map.get(key);
for (String value : values) {
System.out.print(value + " ");
}
System.out.println();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//GET请求逻辑
//...
System.out.println("------------");
String[] hobbies = req.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println(hobby);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//GET请求逻辑
//...
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username);
System.out.println(password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
POST only needs to use the method of GET
public class RequestDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//采用request提供的获取请求参数的通用方式来获取请求参数
//编写其他的业务代码...
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
3. Request request forwarding
Request forwarding (forward): a resource jump method inside the server
(1) The browser sends a request to the server, and the corresponding resource A in the server receives the request
(2) Resource A sends the request to resource B after processing the request
(3) Resource B responds to the browser after processing the result
(4) The process of requesting from resource A to resource B is called request forwarding
Implementation of request forwarding
req.getRequestDispatcher("资源B路径").forward(req,resp);
Request to share data between forwarding resources: use the Request object
Store data to the request field [range, data is stored in the request object]
void setAttribute(String name,Object o);
Get the value according to the key
Object getAttribute(String name);
Delete the key-value pair according to the key
void removeAttribute(String name);
Features of Request Forwarding
The browser address bar path does not change
Can only be forwarded to internal resources of the current server
One request, you can use request to share data between forwarding resources
3. Response
Response: Use the response object to set the response data
Reponse's inheritance system is also very similar to Request's inheritance system:
1. Response setting response data function
The HTTP response data is divided into three parts in total, namely the response line, response header, and response body
① Response line
Set response status code:
void setStatus(int sc);
②Response header
Set the response header key-value pair:
void setHeader(String name,String value);
③Response body
For the response body, it is written to the browser through the output stream of characters and bytes
Get character output stream:
PrintWriter getWriter();
get byte output stream
ServletOutputStream getOutputStream();
2. Request redirection
(1) The browser sends a request to the server, and the corresponding resource A in the server receives the request
(2) Resource A cannot process the request now, it will respond to the browser with a status code of 302 + a path to access resource B at location (3) The browser will resend the request to the access address corresponding to the location to access resource B after receiving the response status code of 302 (4) After resource B receives the request, it will process it and finally respond to the browser. This whole process
is
called
redirection
How to implement redirection:
resp.setStatus(302);
resp.setHeader("location","资源B的访问路径");
Redirection simplified:
resposne.sendRedirect("资源B的访问路径");
Redirect Features:
Browser address bar path sending changes
When redirecting access, the address will change due to two requests sent by the browser
Resources that can be redirected to any location (both service content and external)
because the first response result contains the path that the browser will jump to next time, so this path can be a resource at any location.
Two requests cannot be used to share data in multiple resources.
Because the browser sends two requests, which are two different request objects, data cannot be shared through the request object
.
Comparison of Request and Response redirection
3. Path problem
When forwarding, /request-demo is not added to the path, but redirection is added.
Browser use: need to add a virtual directory (project access path)
Server use: no need to add a virtual directory
4. Response response character data
Get the character output stream through the Response object: PrintWriter writer = resp.getWriter();
Write data through the character output stream: writer.write("aaa")
① can return a simple string
②It can return a string of html strings and can be parsed by the browser
③ Chinese character strings can be returned, and attention should be paid to setting the encoding of the response data as utf-8
//设置响应的数据格式及数据的编码
response.setContentType("text/html;charset=utf-8");
5. Response response byte data
Obtain the byte output stream through the Response object: ServletOutputStream outputStream =
resp.getOutputStream();
Write data through the byte output stream: outputStream.write(byte data);
//1. 读取文件
FileInputStream fis = new FileInputStream("d://a.jpg");
//2. 获取response字节输出流
ServletOutputStream os = response.getOutputStream();
//3. 完成流的copy
byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff))!= -1){
os.write(buff,0,len);
}
fis.close();