当前位置:网站首页>Request (request object) and response (response object)
Request (request object) and response (response object)
2022-07-06 04:44:00 【Tian Yijun】
1. Overview of requests and responses :
The concept of request : Enter the address in the browser address field , Click enter to request the server , This process is a request process .
The concept of response : The server sends the request according to the browser , Return the data to the browser for display on the web page , This process is called response
2.HttpServletResponse object
HttpServletResponse It's an interface , Its parent interface is ServletResponse, Commonly used in development HttpServletResponse
The response information is divided into three parts : Response line 、 Response head 、 Response Content ( Response body )
1. Related methods of sending status code :
>>> Set status code
setStatus(ing sc): The parameter is the status code .// The default is 200
setStatus(int sc,String sm):sc Table status code ,sm Table description of status code
Common status codes :
200: Corresponding success
302: Redirect
404: Requested resource not found
500: An exception occurred in the server code
>>> Error message method :
senError(int sc): Parameters are also status codes
senError(int sc,String sm):sc Table status code ,sm Table description of status code
such as :response.sendError(404,"chapter04 The requested resource for the project does not exist ");
1.2 Methods related to sending response message headers :
The data format of the response header :key-value In the form of , There is a key One value, There is a key Multiple value
>>>1. Set the response header :
* One key, Corresponding to one value
setHeader(String key,String value);
such as :
setHeader("aa","AA");
If :setHeader("aa","AA");
setHeader("aa","BB");
final result :aa The corresponding value of this header is BB
* One key Corresponding multiple value
addHeader(String key,String value);
for example :addHeader("aa","AA");
addHeader("aa","BB");
final result :aa The value used for this head pair is AA and BB
such as :// Methods related to the response header
// In case of wrong user name and password , Go back to the login page and let the user restart the data
//1. Set status code
response.setStatus(302);
//2. Set the response header , Complete redirection to the login page
response.setHeader("Location","chapter04/login.html");
>>>2. Set the length of the response data :setContentLength(int src) Method
>>>3. Set the method to deal with garbled code :
1.setCharacterEncoding(String a); Parameter is a code table format , such as :utf-8
2.setContenType(String a); Parameters represent the type and code table format of response data , such as :"text/thml;charset=utf-8"
1.3 Send methods related to the response body
1.getOutputStream, adopt response Return pictures to the browser 、 Binary files such as video , Of course, you can also return text data to the browser
such as :
//** byte ** Stream object , Return data to the browser
ServletOutputStream out=response.getOutputStream();
String value="itcast";
out.write(value.getBytes());
2.getWriter(), Usually response Return text data to the browser , Cannot return pictures to the browser 、 Video and other binary files
such as :
//** character ** Output data to browser
PrintWriter pw=response.getWriter();
String value="itcast-----";
//pw.print(value);
pw.write(value);
1.4 Solve the problem of garbled Chinese output
1. The byte stream will appear garbled in the browser output first
reason : It is caused by the inconsistency between the server-side encoding format and the browser encoding format
such as :
// 1. Handle the Chinese garbled code problem of byte stream
String data=" China ";
ServletOutputStream out=response.getOutputStream();
// Deal with the mess : The short encoding of the server is consistent with that of the browser .
// Let the browser side coding also utf-8
// Let the Chinese coding format on the server side be utf-8, Make sure there's consistency
response.setHeader("Content-Type","text/html;charset=utf-8");
out.write(data.getBytes());
**** There are two ways to deal with the Chinese garbled code of byte stream
1.response.setHeader("Content-Type","text/html;charset=utf-8");
2.response.setContentype("text/html;charset=utf-8");
2. Characters flow to browser output at noon , There will also be garbled code
Two forms of garbled code :??, This question mark indicates that the Chinese coding format is iso8859-1 code , This encoding format does not support Chinese
Handle : Keep the coding of browser and server consistent
such as :
// 1. Handle the Chinese garbled code problem of character stream
//2. Handle The encoding of the server , Let this code support Chinese
response.setCharacterEncoding("utf-8");
//3. Handle browser side coding
response.setHeader("Content-Type","text/html;charset=utf-8");
String data=" China ";
//4. Get character stream
PrintWriter pw=response.getWriter();
pw.print(data);
**** There are two ways to deal with the Chinese garbled code problem of character stream
1.response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type","text/html;charset=utf-8");
2.response.setContentype("text/html;charset=utf-8");
Conclusion : It is used in dealing with the problem of Chinese garbled code output from character stream and byte stream response.setHeader("Content-Type","text/html;charset=utf-8");
Be careful :
1. Common encoding formats :GBK、GB18030、GB2312 Both support Chinese coding format , Of course, some other characters are supported
2.utf-8 Universal code table format , All characters are supported
3.ISO8859-1: No Chinese support
1.5 Realize the regular jump and refresh of web pages :
Timed jump : Jump from a registration page to a login page , Enter the previously registered user name and password .
for example :
// after 5 Seconds to jump to “login.html”
response.setHeader("Refresh","5;URL=/chapter04/login.html");
Refresh regularly : The address on the current page does not change , But the current page refreshes itself regularly , Page data changes .
for example :
// Is it realized 5 Refresh every second
response.setHeader("Refresh","5");
// Convenient for observation , Output a time , Find every time 5 Seconds will refresh, and then the time will change
response.getWriter().print(new Date());
1.6 Implement redirection
Implement redirection related methods
>>>1:302 and Location In combination with , Implement redirection
response.setStatus(302);
response.setHeader("Refresh","5;URL=/chapter04/login.html");
>>>2:sendRediret("/chapter04/login.html");
Redirection is done through login cases :
Demand analysis : Enter your user name and password on the login page , stay LoginServlet Inside , Determine whether the user and password are correct .
If the input is wrong , Will be redirected to the login page , If correct , Jump to the welcome page .
Get the user name and password submitted on the login page :request.getParameter() Method ;
Features of redirection :1. Browser address bar changes
2. Send two requests , Are all requests sent by the browser
Redirected path : Because the request is sent by the browser . So you must bring the project name , such as :/chapter04/welcome.html;
3.HttpServletRequest Request object
HttpServletRequest It's an interface , Its parent interface ServletRequest, In development , Commonly used is the request object with protocol
The request message : Request line 、 Request header 、 Request parameters
1. Get the relevant method of the request line message :
Common request line methods :
>>>1. Get the method of Request Submission :getMethod();
>>>2. Get the requested protocol :getProtocol();
>>>3. Get the project name :getContextPath(); // Get the URL”
>>>4. obtain servlet route getServletPath();
>>>5. Get the request path :getRequsetURI(),getRequestURL();
uri Corresponding value :/ Project name /servlet route
url Corresponding value :http://localhost:8080/uri
2. Get the method related to the request header :
>>>1. According to the message header , Get value :String value=getHeader( The name of the message header );
>>>2. Get all headers :Enumeration er=getHeaderName();
3. Get the method related to the request parameters :
>>>1. according to name Property value , Get the value entered by the user :String value=getParameter(name The value of the property );
>>>2. according to name Property value , Get the value selected by the user :String[] values=getParameterValues(name The value of the property );
>>>3. No parameters , Get all values :Map<String,String[]> map=getParameterMap();
4. Solve the problem of Chinese garbled code of request parameters :
Case one : Handle get Chinese garbled code submitted by
The use of string The construction method of solves Chinese garbled code :new String( Byte array , Coding format );
Code : String newvalue = new String(value.getBytes("IS08859-1"), "utf-8");
The second case : Handle post Chinese garbled problem of request :
post Submit , Will first submit the parameters to request Object , The default encoding of the buffer is IS08859-1, No Chinese support
processing method : hold request The encoding of the buffer is set to support Chinese code table format .
Code :request.setCharacterEncoding("utf-8");
5. adopt Requset Object passing data
The concept of domain objects : To a certain extent , You can store values and take values .
request Domain object : In a request , You can store values and take values
>>> Store value :setAttribute(String key,0bject obj);
>>> Value : getAttribute(string key);
>>> remove :removeAttribute(String key);
1.2 RequestDispatcher Interface
In development, access to a web After resources , The server needs to jump to another resource to process the request , Can pass sendRedirect Redirect
Method to implement , It's fine too RequestDispatcher The of the forwarding object forward Method to implement .
Get the forwarding object : RequestDispatcher forwardObj = request.getRequestDispatcher(" The path to another resource ");
Common methods :
>>>1. Implement request forwarding :forward0bj.forward(request,response);
>>> 2. The implementation request contains :forwardObj.include(request,response);
1. Request forwarding :
characteristic : Sent a request , Respond once , and request Use with domain objects , Can achieve worth passing .
Forwarding path : The forwarding action is implemented inside the server , Therefore, the forwarding path should not carry the project name
Ask for redirection :
characteristic : Two requests were sent , Responded twice , Unable to join request Use with domain objects .
Redirection path : The redirection action is executed on the browser side , Therefore, the path needs to carry the project name .
2. Request includes
Request includes : Done inside the server , The path does not need to carry the project name .
characteristic : Send a request , Request inclusion is done by the server
Request contains path : Done inside the server , The path does not need to carry the project name .
The difference between redirection and forwarding :
1. Redirection is two requests , Two responses , Forwarding is a request , One response
2. The first request parameter of redirection will disappear in the second time , Forwarding will not disappear
3. The address bar will change after the redirection request , The address bar will not change after forwarding the request
4. Redirection can access the address outside the stack , Forwarding is not allowed
5. Forwarding first proportion orientation is relatively safe
In forwarding forward and include The difference between :( repair )
1.forward The browser part of the current page will be ignored later , Then display the browser part of the page after jump
2.include The browser part of the following current page will be added after the browser part of the page after jump
边栏推荐
- Distributed transaction solution
- Etcd database source code analysis -- etcdserver bootstrap initialization storage
- Word cover underline
- [HBZ sharing] how to locate slow queries in cloud database
- 力扣(LeetCode)186. 翻转字符串里的单词 II(2022.07.05)
- 拉格朗日插值法
- . Net interprocess communication
- Project manager, can you draw prototypes? Does the project manager need to do product design?
- Postman关联
- Knowledge consolidation source code implementation 3: buffer ringbuffer
猜你喜欢
CADD course learning (7) -- Simulation of target and small molecule interaction (flexible docking autodock)
Recommendation | recommendation of 9 psychotherapy books
[detailed steps of FreeRTOS shift value for the first time]
比尔·盖茨晒18岁个人简历,48年前期望年薪1.2万美元
How do programmers teach their bosses to do things in one sentence? "I'm off duty first. You have to work harder."
Uva1592 Database
Programmers' position in the Internet industry | daily anecdotes
How to estimate the population with samples? (mean, variance, standard deviation)
Postman关联
Yyds dry inventory automatic lighting system based on CC2530 (ZigBee)
随机推荐
比尔·盖茨晒18岁个人简历,48年前期望年薪1.2万美元
[HBZ share] reasons for slow addition and deletion of ArrayList and fast query
麦斯克电子IPO被终止:曾拟募资8亿 河南资产是股东
ue5 小知识 FreezeRendering 查看视锥内渲染的物体
[mathematical modeling] differential equation -- sustainable development of fishing industry
项目经理,你会画原型嘛?项目经理需要做产品设计了?
It is also a small summary in learning
Distributed transaction solution
SQL注入漏洞(MSSQL注入)
Easyrecovery靠谱不收费的数据恢复电脑软件
SharedPreferences source code analysis
Etcd database source code analysis -- etcdserver bootstrap initialization storage
The implementation of the maize negotiable digital warehouse receipt standard will speed up the asset digitization process of the industry
也算是學習中的小總結
Ue5 small knowledge freezerendering view rendered objects in the cone
[face recognition series] | realize automatic makeup
11. Intranet penetration and automatic refresh
动态规划(树形dp)
How to realize automatic playback of H5 video
Database - MySQL storage engine (deadlock)