当前位置:网站首页>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
边栏推荐
- Fourier series
- Leetcode brush question: dynamic planning 09 (weight of the last stone II)
- Monotonic stack - 739. Daily temperature
- 测试用例管理工具
- LeetCode 0141. 环形链表 - 三种方法解决
- Analysis of static broadcast transmission process
- Classification cluster analysis
- 一名合格的软件测试工程师,应该具备哪些技术能力?
- [prototype and prototype chain] get to know prototype and prototype chain~
- Detailed explanation of string + memory function (C language)
猜你喜欢

Lightpicture - exquisite drawing bed system

From Clickhouse to Snowflake: MPP query layer

Advanced Mathematics (Seventh Edition) Tongji University exercises 3-6 personal solutions

Simple and easy-to-use performance testing tools recommended

Is there a bonus period for robot engineering

Dynamic planning - 63. Different paths II

R notes mice

Ch340 RTS DTR pin programming drives OLED

TypeError: ufunc ‘bitwise_ and‘ not supported for the input types, and the inputs could not be safely

《剑指offer》| 刷题小记
随机推荐
Simple and easy-to-use performance testing tools recommended
Data mining-02
leetcode刷题:动态规划08(分割等和子集)
STC timer is abnormal (how to modify the initial value, the timing time is 100ms)
超好用的 PC 端长截图工具
Tungsten Fabric SDN — BGP as a Service
Recursion and non recursion are used to calculate the nth Fibonacci number respectively
The latest version of pagoda installs the zip extension, and PHP -m does not display the processing method
jdbc使用
In depth introduction to sap ui5 fileuploader control - why do you need a hidden iframe trial
数据挖掘-01
Dynamic programming - 416. Segmentation and subsets
2022.7.13-----leetcode.735
How to solve MySQL deep paging problem
Capacity expansion and reduction of RBD block storage device (VI)
What is interface testing and its testing process
基于SSM实现在线租房系统
From Clickhouse to Snowflake: MPP query layer
leetcode刷题:动态规划09(最后一块石头的重量 II)
xml文件使用及解析