当前位置:网站首页>ServletContext、request、response
ServletContext、request、response
2022-07-28 03:56:00 【Program three two lines】
One 、 Context object
1、 summary
ServletContext Official call servlet Context , It's an interface . Created when the server starts , Destroy when the server is shut down , At startup, an object will be created for each project , This object is ServletContext object . This object is globally unique , And everything inside the project servlet All share this object . So it's called global application sharing object .
2、 How to get
adopt servlet Medium init Methods servletConfig Object acquisition

httpservlet Medium direct acquisition ServletContext servletContext = getServletContext();
3、 effect
1. Is a domain object
The domain object is the storage space created by the server in memory , Used in different dynamic resources (servlet) Transfer and share data between , All domain objects have the following 3 A way
setAttribute(name,value);name yes String type ,value yes Object type ; | Add data to the domain object , Add with key-value Form add |
getAttribute(name); | According to the designation key Read the data in the domain object |
removeAttribute(name); | According to the designation key Delete data from the domain object |
2. You can read global configuration parameters
getServletContext().getInitParameter(name);// Get the parameter value according to the specified parameter name
getServletContext().getInitParameterNames();// Get a list of all parameter names
stay web.xml Configure global parameters in
<!-- Global configuration parameter , Because it doesn't belong to any one servlet, But all servlet Both can pass servletContext Read this data -->
<context-param>
<param-name>param1</param-name>
<param-value>value1</param-value>
</context-param>
<context-param>
<param-name>param2</param-name>
<param-value>value2</param-value>
</context-param>In dynamic resources servlet It uses servletcontext Read the global parameter code
ublic void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Use servletContext Read the global configuration parameter data
// The core approach
/*getServletContext().getInitParameter(name);// Get the parameter value according to the specified parameter name
getServletContext().getInitParameterNames();// Get a list of all parameter names */
// Print all parameters
//1. First get the names of all global configuration parameters
Enumeration<String> enumeration = getServletContext().getInitParameterNames();
//2. Ergodic iterator
while(enumeration.hasMoreElements()){
// Get the parameter name of each element
String parameName = enumeration.nextElement();
// Get the parameter value according to the parameter name
String parameValue = getServletContext().getInitParameter(parameName);
// Print
System.out.println(parameName+"="+parameValue);
}
}3. You can search the resource files under the current project directory
getServletContext().getRealPath(path), Get the absolute path of resources on the server according to the relative path
getServletContext().getResourceAsStream(path), Get the input byte stream of resources on the server according to the relative path
4. You can get the current project name ( understand )
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the project name ,getServletContext().getContextPath()
response.getOutputStream().write((" Project name :"+getServletContext().getContextPath()).getBytes());
}Two 、 Request object request
1、 summary
We're creating Servlet It will cover service() Method , or doGet()/doPost(), These methods have two parameters , A request for request And representatives respond response.service() Method is called according to different request methods doget() and dopost().
service Methods request The type is ServletRequest, and doGet/doPost Methodical request type HttpServletRequest,HttpServletRequest yes ServletRequest Sub interface of , More powerful functions and methods
request Operation process

2、 Grab http package , Grasp the request line respectively , Request header , Request body (post The request method will have )

Request line
Get the client's request mode ---StringgetMethod()
web Name of application ---StringgetContextPath()
obtain URL---StringBuffer getRequestURL(); Such as :http://localhost:8080/request/info
obtain URI---String getRequestURI(); Such as :/request/info
Get access to the client IP Address ---request.getRemoteAddr()
obtain get Request parameters ---String getQueryString();
Request header
Get all request header names
// All request header names
Enumeration<String> headerNames = request.getHeaderNames();
// Traverse all request headers
while (headerNames.hasMoreElements()){
// name
String s = headerNames.nextElement();
// The value corresponding to the name
String requestHeader = request.getHeader(s);
System.out.println(requestHeader);
}Get the source of this visit referer
String referer= request.getHeader("referer");
Only by requesting in the following way can we get referer
- Direct use <a href="">
- submit Submit Form
- s Submitted forms (get \post)
Request body

Forwarding and redirection

3、 ... and 、 The response object
Set the response line
response.setState(Int code)
Set the response header
add Yes add new
addHeader(String name,String value)
addIntHeader(String name,int value)
addDateHeader(String name,date)
set The setting already exists
setHeader(String name,String value)
setIntHeader(String name,int value)
setDateHeader(String name,Date value)
Set the response body
1、 adopt write() Method to write
response.getWriter().write("hello test ");
By default, Chinese characters written will be garbled , When saving the written content to the buffer for use ISO8859, and ISO8859 No Chinese support , So random code
// Set the stored code before saving
response.setCharacterEncoding("UTF-8");
// Then tell the browser the encoding used
response.setHeader("Content-Type","text/html;charset=UTF-8");
response.getWriter().write("hello test ");
Be careful
The above can only tell the browser the code used ,tomcat See, it's set to utf-8 It will also be used in storage utf-8
Or directly use the encapsulated method
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("hello test ");2、 adopt OutPutStream() To write
Be careful getWrite() and getOutputSteam Cannot call at the same time
response.setContentType("text/html;charset=UTF-8");
response.getOutputStream().write("hello test ".getBytes());
Redirect
servlet1 There is no such resource , Tell you to find servlet2, Send another request to servlet2, To access the server twice , Status code is 302, The browser address bar has changed
response.setStatus(302);
response.setHeader("location","/userInfo");
Write the status code every time , and location More trouble , It encapsulates a method
response.sendRedirect("/userInfo");Regular refresh redirection
response.setHeader("refresh","5;url=http://www.baidu.com")
url The value of is 5 The address to jump in seconds
边栏推荐
- Prefix-Tuning: Optimizing Continuous Prompts for Generation
- C语言力扣第45题之跳跃游戏 II。遍历跳跃
- STC timer is abnormal (how to modify the initial value, the timing time is 100ms)
- [openvx] VX for basic use of objects_ image
- 【图像分类】2021-MLP-Mixer NIPS
- BRD,MRD,PRD的区别
- 一文读懂Plato Farm的ePLATO,以及其高溢价缘由
- Interview essential skills: SQL query special training!
- 【无标题】
- Monotonic stack - 739. Daily temperature
猜你喜欢

Ch340 RTS DTR pin programming drives OLED

过滤器、拦截器、监听器

MySQL Basics (create, manage, add, delete, and modify tables)

Detailed explanation of pointer written test questions (C language)

LightPicture – 精致图床系统

Appnium -- app automated test tool

C语言:求一个整数存储在内存中的二进制中1的个数

How to solve MySQL deep paging problem

Super easy to use PC end long screenshot tool

【无标题】
随机推荐
cookie与Session
I did these three things before the interview, and the result was actually direct
Qt:qmessagebox message box, custom signal and slot
What is interface testing and its testing process
Leetcode 0140. word splitting II
WordPress simple mkblog blog theme template v2.1
ES6 from entry to mastery 07: Deconstruction assignment
搬家通知!
【无标题】
构建“产业大脑”,以“数字化”提升园区运营管理及服务能力!
C语言力扣第45题之跳跃游戏 II。遍历跳跃
Interface automation test, complete introduction
Selenium--WEB自动化测试工具
LabVIEW loads and uses custom symbols in tree control projects
Appnium--APP自动化测试工具
Build an "industrial brain" and improve the park's operation, management and service capabilities with "digitalization"!
Leetcode 0141. circular linked list - three solutions
数据挖掘-01
After 95, Alibaba P7 published the payroll: it's really heartbreaking
Leetcode brush question: dynamic planning 09 (weight of the last stone II)