Servlet
1、继承结构
顶级Servlet接口
//初始化
void init(ServletConfig var1) throws ServletException;
//得到配置内容 ServletConfig对象
ServletConfig getServletConfig();
//处理用户请求的方法
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
//返回Servlet字符串描述信息的方法
String getServletInfo();
//销毁方法
void destroy();
GenericServlet 抽象类 一些实现的方法
private transient ServletConfig config;
//返回配置类对象
public ServletConfig getServletConfig() {
return this.config;
}
//初始化 可以将配置信息添加到当前实例中,实例化时 初始化使用的是该函数
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();//调用无参的init方法
}
//我们要初始化的是无参的init方法,这样可以不用管config对象,也可以定义自己需要实现的init方法
public void init() throws ServletException {
}
HttpServlet 抽象类
//实现了service方法,将Servlet对象强转为HttpServlet对象。
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
} catch (ClassCastException var6) {
throw new ServletException(lStrings.getString("http.non_http"));
}
this.service(request, response);
}
如果我们继承了Httpserlet 可以重写service方法,也可以重写doget或者dopost等方法。
2、ServletConfig对象
为Servlet提供初始配置参数的一种对象,每个Servet都有自己独立唯一的Servletconfig对象
。容器会为每个Servlet实例化一个Servletconfig对象,并通过Servlet生命周期的init方法传入给serviet作为属性。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<servlet>
<servlet-name>userServlet</servlet-name>
<servlet-class>com.cky.servlet.UserServlet</servlet-class>
<init-param>
<param-name>kaya</param-name>
<param-value>valuea</param-value>
</init-param>
<init-param>
<param-name>kayb</param-name>
<param-value>valueb</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>userServlet</servlet-name>
<url-pattern>/userservlet</url-pattern>
</servlet-mapping>
</web-app>
package com.cky.servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
//配置多个url路径 使用value 是一样饿效果
//@WebServlet(urlPatterns ={"/s1","/s2"})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletConfig servletConfig=this.getServletConfig();
Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
while(initParameterNames.hasMoreElements()){
String s = initParameterNames.nextElement();
System.out.println(s); //kaya
// kayb
}
}
}
注解方式
package com.cky.servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
//配置多个url路径 使用value 是一样饿效果
@WebServlet(urlPatterns ={"/s1","/s2"},
initParams = {@WebInitParam(name ="kaya",value = "vlauea"),
@WebInitParam(name="keyb",value = "vb")})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletConfig servletConfig=getServletConfig();
Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
while (initParameterNames.hasMoreElements()){
String s = initParameterNames.nextElement();
String initParameter = servletConfig.getInitParameter(s);
System.out.println(s+"--->"+initParameter);//keyb--->vb
//kaya--->vlauea
}
}
}
3 、ServletContext
Servletcontext对象有称呼为上下文对象,或者叫应用域对象(后面统一讲解域对象)。容器会为每个app创建一个独立的唯-的Servletcontext对象
。ServletContext对象为所有的Servlet所共享
ServletContext可以为所有的Servlet提供初始配置参数
package com.cky.servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
//配置多个url路径 使用value 是一样饿效果
//@WebServlet(urlPatterns ={"/s1","/s2"})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ServletContext servletContext=this.getServletContext();
ServletContext servletContext=getServletContext();
Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
while(initParameterNames.hasMoreElements()){
String s = initParameterNames.nextElement();
String initParameter = servletContext.getInitParameter(s);
System.out.println(s+"-->"+initParameter); //code-->i
}
}
}
<context-param>
<param-name>code</param-name>
<param-value>i</param-value>
</context-param>
3.1 获得路径
package com.cky.servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
//配置多个url路径 使用value 是一样饿效果
//@WebServlet(urlPatterns ={"/s1","/s2"})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ServletContext servletContext=this.getServletContext();
ServletContext servletContext=getServletContext();
//获得文件的部署路径 在磁盘中目录位置
String upload = servletContext.getRealPath("upload");// E:\java_code\web_all\out\artifacts\web02_war_exploded\upload
System.out.println(upload);
//获得项目的上下文路径 / 访问路径
String contextPath = servletContext.getContextPath();
System.out.println(contextPath); // web02
}
}
3.2 域对象相关API
ServletContext 是最大的一个域对象,应用中所有的Servlet共享域对象中的内容。
package com.cky.servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
//配置多个url路径 使用value 是一样饿效果
@WebServlet(urlPatterns ={"/s1","/s2"},
initParams = {@WebInitParam(name ="kaya",value = "vlauea"),
@WebInitParam(name="keyb",value = "vb")})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext=getServletContext();
servletContext.setAttribute("ka",2);
}
}
package com.cky.servlet;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns ={"/s3",})
public class UserServlet1 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext=getServletContext();
int ka = (int)servletContext.getAttribute("ka");
System.out.println(ka); //2
}
}
先运行UserServlet 设置值,之后运行UserServlet1获得属性值,如果先执行UserServlet1,会获得null。
4、HttpServletRequest
4.1 获得请求行和请求头相关api
package com.cky.servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
//配置多个url路径 使用value 是一样饿效果
@WebServlet(urlPatterns ={"/s1","/s2"},
initParams = {@WebInitParam(name ="kaya",value = "vlauea"),
@WebInitParam(name="keyb",value = "vb")})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//行相关 Get/POST URI HTTP/1.1
System.out.println(req.getMethod());//请求方式 GET
System.out.println(req.getScheme());//请求协议 http
System.out.println(req.getProtocol());//请求协议和版本 HTTP/1.1
System.out.println(req.getRequestURI());//资源标识符 /web02/s1
System.out.println(req.getRequestURL());//资源定位符 http://localhost:8081/web02/s1
System.out.println(req.getLocalPort());//本应用容器端口号 8081
System.out.println(req.getServerPort()); //客户端发请求的端口号 与上一个可能不同,因为中间可能经过代理 8081
System.out.println(req.getRemotePort()); //客户端软件端口号 53389
//头相关
System.out.println(req.getHeader("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 s = headerNames.nextElement();
System.out.println(s+":"+req.getHeader(s));
}
}
}
4.2 请求中键值对相关api
http://localhost:8081/web02/s1?username=cky&passward=123&hobby=篮球&hobby=sing
package com.cky.servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
//配置多个url路径 使用value 是一样饿效果
@WebServlet(urlPatterns ={"/s1","/s2"},
initParams = {@WebInitParam(name ="kaya",value = "vlauea"),
@WebInitParam(name="keyb",value = "vb")})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取单个参数
String username = req.getParameter("username"); //cky
System.out.println(username);
//获取多个值
String[] hobbies = req.getParameterValues("hobby");
System.out.println(Arrays.toString(hobbies)); // [篮球, sing]
//获取所有参数名
Enumeration<String> parameterNames = req.getParameterNames();
while (parameterNames.hasMoreElements()) {
String pname = parameterNames.nextElement();
String[] parameterValues = req.getParameterValues(pname);
if(parameterValues.length>1){
System.out.println(Arrays.toString(parameterValues));
}
else
System.out.println(parameterValues[0]);
}
// cky
// 123
// [篮球, sing]
//获得参数的 Map集合
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[] parameterValues = req.getParameterValues(key);
if (parameterValues.length > 1) {
System.out.println(Arrays.toString(parameterValues));
} else
System.out.println(parameterValues[0]);
}
// cky
// 123
// [篮球, sing]
}
}