目录
一、ServletConfig
二、ServletContext
三、ServletContext其他重要API
(一)获取文件路径和上下文
(二)域对象的相关API
四、HttpServletRequest常见API
(一)获取请求行/头信息相关
(二)获得请求参数相关
五、HttpServletResponse常见API
一、ServletConfig
ServletConfig的概念:
为Servlet提供初始配置参数的一种对象,每个Servlet都有自己独立唯一的ServletConfig对象
容器会为每个Servlet实例化一个ServletConfig对象,并通过Servlet生命周期的init方法传入给Servlet作为属性
新建Web项目:
Servlet1:
// 可以通过注解替代在web.xml配置
@WebServlet(urlPatterns = "/servlet1",initParams = {@WebInitParam(name = "keya", value = "valueA"),@WebInitParam(name = "keyb", value = "valueB")})
public class Servlet1 extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("------------------------ServletConfig获取参数----------------------------");ServletConfig servletConfig = getServletConfig();// 获取初始配置信息即可// 根据参数名获取参数值String keya = servletConfig.getInitParameter("keya");System.out.println("keya:" + keya);// 获取所有的初始参数的名字// hasMoreElements 判断有没有下一个参数 如果有返回true 如果没有返回false// nextElement 1 取出下一个元素 2 向下移动游标Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();while (initParameterNames.hasMoreElements()) {String pname = initParameterNames.nextElement();System.out.println(pname + "=" + getInitParameter(pname));} }
}
Servlet2:
@WebServlet(urlPatterns = "/servlet2",initParams = {@WebInitParam(name = "keyc", value = "valueC"),@WebInitParam(name = "keyd", value = "valueD")})
public class Servlet2 extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("------------------------ServletConfig获取参数------------------");ServletConfig servletConfig = getServletConfig();String keyc = servletConfig.getInitParameter("keyc");System.out.println("keyc:" + keyc);Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();while (initParameterNames.hasMoreElements()) {String panme = initParameterNames.nextElement();System.out.println(panme + "=" + getInitParameter(panme));}}
}
tomcat配置:
启动tomcat:
http://localhost:8080/demo03/servlet1
http://localhost:8080/demo03/servlet2
二、ServletContext
ServletContext概念:
ServletContext对象有称呼为上下文对象,或者叫应用域对象(后面统一讲解域对象)
容器会为每个app创建一个独立的唯一的ServletContext对象
ServletContext对象为所有的Servlet所共享
ServletContext可以为所有的Servlet提供初始配置参数
Servlet1和Servlet2分别加入以下代码:
System.out.println("--------------------ServletContext获取参数---------------------");
ServletContext servletContext1 = getServletContext();
ServletContext servletContext2 = servletConfig.getServletContext();
ServletContext servletContext3 = req.getServletContext();
System.out.println(servletContext1 == servletContext2);
System.out.println(servletContext3 == servletContext2);
String encoding = servletContext1.getInitParameter("encoding");
System.out.println("encoding:" + encoding);
// 如果不知道ServletContext的参数名
Enumeration<String> parameterNames = servletContext1.getInitParameterNames();
while (parameterNames.hasMoreElements()) {String pname = parameterNames.nextElement();System.out.println(pname + "=" + servletContext1.getInitParameter(pname));
}
web.xml添加配置信息:
<context-param><param-name>encoding</param-name><param-value>UTF-8</param-value>
</context-param>
<context-param><param-name>username</param-name><param-value>zhangsan</param-value>
</context-param>
启动tomcat:
http://localhost:8080/demo03/servlet1
http://localhost:8080/demo03/servlet2
三、ServletContext其他重要API
(一)获取文件路径和上下文
@WebServlet("/servlet3")
public class Servlet3 extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletContext servletContext = req.getServletContext();// 获得一个指向项目部署位置下的某个文件/目录的磁盘真实路径的APIString path = servletContext.getRealPath("upload");System.out.println(path);// G:\develop\workspace\atguigujavaweb\one\basecode\out\artifacts\demo03_servletConfig_servletContext_war_exploded\upload// 获得项目部署的上下文路径:项目的访问路径String contextPath = servletContext.getContextPath();System.out.println(contextPath); // /demo03}
}
(二)域对象的相关API
域对象:一些用于存储数据和传递数据的对象,传递数据不同的范围,我们称之为不同的域,不同的域对象代表不同的域,共享数据的范围也不同。
ServletContext代表应用,所以ServletContext域也叫作应用域,是webapp中最大的域,可以在本应用内实现数据的共享和传递。
webapp中的三大域对象,分别是应用域、会话域、请求域。
API | 功能解释 |
---|---|
void setAttribute(String key,Object value); | 向域中存储/修改数据 |
Object getAttribute(String key); | 获得域中的数据 |
void removeAttribute(String key); | 移除域中的数据 |
Servlet1中添加代码:
servletContext1.setAttribute("key","value");
servletContext1.setAttribute("key","valueA");
servletContext1.removeAttribute("key");
Servlet2中添加代码:能够获取到Servlet1设置的值
// 从域对象中读取数据
String key = (String) servletContext1.getAttribute("key");
System.out.println(key);
四、HttpServletRequest常见API
(一)获取请求行/头信息相关
@WebServlet("/servlet4")
public class Servlet4 extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 行相关 GET/POST uri http/1.1System.out.println(req.getMethod()); // 获取请求方式 GETSystem.out.println(req.getScheme()); // 获取请求协议 httpSystem.out.println(req.getProtocol()); // 获取请求协议及版本 HTTP/1.1System.out.println(req.getRequestURI()); // 获取请求uri 项目内的资源路径 /demo03/servlet4System.out.println(req.getRequestURL()); // 获取请求的url 项目内资源完整的路径 http://localhost:8080/demo03/servlet4/*** URI:用于标识资源,可以是互联网上的,也可以是其他类型的资源。/demo03/servlet4* URL:用于在互联网上定位和访问资源,是实现资源访问的具体路径。http://localhost:8080/demo03/servlet4*/System.out.println(req.getLocalPort()); // 本应用容器的端口号 8080System.out.println(req.getServerPort()); // 客户端发请求时使用的端口号 8/080System.out.println(req.getRemotePort()); // 客户端软件的端口号 5391// 头相关 key:value key:value ... ...// 根据名字单独获取某个请求头String accept = req.getHeader("Accept");System.out.println("Accept:" + accept);// Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7// 获取本次请求中所有的请求头的名字Enumeration<String> headerNames = req.getHeaderNames();while (headerNames.hasMoreElements()) {String hname = headerNames.nextElement();System.out.println(hname + ":" + req.getHeader(hname));}}
}
(二)获得请求参数相关
API | 功能解释 |
---|---|
String getParameter(String parameterName); | 根据请求参数名获取请求单个参数值 |
String[] getParameterValues(String parameterName); | 根据请求参数名获取请求多个参数值数组 |
Enumeration<String> getParameterNames(); | 获取所有请求参数名 |
Map<String, String[]> getParameterMap(); | 获取所有请求参数的键值对集合 |
BufferedReader getReader() throws IOException; | 获取读取请求体的字符输入流,例如读取Json |
ServletInputStream getInputStream() throws IOException; | 获取读取请求体的字节输入流,例如读取文件 |
int getContentLength(); | 获得请求体长度的字节数 |
@WebServlet("/servlet5")
public class Servlet5 extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 获取键值对形式的参数// 根据参数名获取单个参数值String username = req.getParameter("username");System.out.println(username);String password = req.getParameter("password");System.out.println(password);// 根据参数名获取多个参数值String[] hobbies = req.getParameterValues("hobby");System.out.println(Arrays.toString(hobbies));// 获取所有的参数名Enumeration<String> parameterNames = req.getParameterNames();while (parameterNames.hasMoreElements()) {String pname = parameterNames.nextElement();String[] values = req.getParameterValues(pname);if (values.length > 1) {System.out.println(pname + "=" + Arrays.toString(values));} else {System.out.println(pname+"="+values[0]);}}// 返回所有参数的map集合 key = 参数名 value = 参数值Map<String, String[]> parameterMap = req.getParameterMap();Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();for (Map.Entry<String, String[]> entry : entries) {String key = entry.getKey();String[] values = entry.getValue();if (values.length > 1) {System.out.println(key + "=" + Arrays.toString(values));} else {System.out.println(key+"="+values[0]);}}System.out.println(req.getServletPath()); }
}
index.html:
<form action="servlet5" method="post">用户名:<input type="tel" name="username"><br>密码:<input type="password" name="password"><br>爱好:<input type="checkbox" name="hobby" value="1">足球<input type="checkbox" name="hobby" value="2">篮球<input type="checkbox" name="hobby" value="3">排球<input type="checkbox" name="hobby" value="4">羽毛球<br><input type="submit">
</form>
运行结果:
以上API专门用于获取key=value形式的参数,无论这些参数是在url后,还是在请求体中。
五、HttpServletResponse常见API
@WebServlet("/servlet6")
public class Servlet6 extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 设置响应行相关的API HTTP/1.1 200/404/405/505/...resp.setStatus(200);String info = "<h1>hello</h1>";// 设置响应头相关的APIresp.setHeader("aaa", "valueA");resp.setContentType("text/html");resp.setCharacterEncoding("UTF-8");resp.setContentLength(info.getBytes().length);// 设置响应体相关的APIPrintWriter writer = resp.getWriter();writer.write(info);// 获得一个向响应体中输入二进制信息的字节输出流// ServletOutputStream outputStream = resp.getOutputStream();}
}