Servlet
- 添加依赖和插件
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!--Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!--配置虚拟目录-->
<path>/</path>
<!--tomcat的端口号。默认是8080-->
<port>80</port>
<!--防止get请求时url中包含中文的乱码问题-->
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
-
执行流程
- 通过ip和端口找到tomcat
- 通过虚拟目录找到某一个项目
- 通过资源路径找到某一个Servlet
- 执行service()方法
-
Servlet三种实现方式
-
实现Servlet接口
-
重写Servlet的所有方法
@WebServlet("/servlet01") public class MyServlet implements Servlet { @Override public void init(ServletConfig servletConfig) throws ServletException { } @Override public ServletConfig getServletConfig() { return null; } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("hello world servlet01"); } @Override public String getServletInfo() { return null; } @Override public void destroy() { } }
-
-
继承GenericServlet类
-
重写service()方法
@WebServlet("/servlet02") public class MyServlet02 extends GenericServlet { @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("hello world servlet02"); } }
-
-
继承HttpServlet类
-
重写doXXX()方法
@WebServlet("/servlet03") public class MyServlet03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("hello world servlet03"); } }
-
-
-
Servlet生命周期
-
init():默认情况下,当Servlet第一次被请求,tomcat会自动创建实例,调用init()方法,该Servlet只创建一次
- 可以通过loadOnStartUp属性修改默认行为
- 大于等于0创建,当服务器启动的时候创建Servlet对象
-
servie():每当tomcat接收到一个Servlet 请求,这个Servlet的service()方法就会被调用一次
-
destory():当服务器把某个Servlet移除或服务器关闭时会调用destory()方法,该方法只能执行一次
-
-
urlPatterns
- 完全路径匹配
- /xxx/YYY
- 大小写敏感
- 目录匹配
- /*
- /aaa/*
- 扩展名匹配
- *.xxx
- 缺省匹配/默认匹配
- /
- 如果一个路径与已知的servlet路径都不匹配,则会走默认匹配
- 完全路径匹配
Request&Response
-
体系结构
-
request常用API
-
获取请求行
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求方法 String method = req.getMethod(); System.out.println("获取请求方式:"+method); //动态获取虚拟目录(主机和端口之后,参数之前的部分) String uri = req.getRequestURI(); System.out.println("获取虚拟目录"+uri); //获取url(包含协议、主机、端口和虚拟目录) StringBuffer url = req.getRequestURL(); System.out.println("获取完整url"+url); System.out.println(url.toString()); //获取请求参数 String queryString = req.getQueryString(); System.out.println("获取所有请求参数:"+queryString); //获取指定的请求参数 String username = req.getParameter("username"); System.out.println("获取指定请参数username:"+username); //获取请求者的ip String remoteAddr = req.getRemoteAddr(); System.out.println("获取请求者的ip地址:"+remoteAddr); }
-
获取请求头
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取所有请求头字段并找到对应的值 Enumeration<String> headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()){ String name = headerNames.nextElement(); System.out.println(name+"="+req.getHeader(name)); } }
-
获取请求体
-
通过字节流读取
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //读取字节流读取请求体数据 ServletInputStream is = req.getInputStream(); int len; byte[] bytes=new byte[1024]; while ((len=is.read(bytes))!=-1){ String s = new String(bytes, 0, len); System.out.println(s); } }
-
通过字符流读取
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //读取字符流读取请求体数据 BufferedReader reader = req.getReader(); String line; while ((line=reader.readLine())!=null){ System.out.println(line); } }
-
-
获取请求参数
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取所有参数的键值对 Map<String, String[]> parameterMap = req.getParameterMap(); System.out.println(parameterMap); //获取所有参数名数组 Enumeration<String> parameterNames = req.getParameterNames(); while (parameterNames.hasMoreElements()){ System.out.println(parameterNames.nextElement()); } //获取指定参数名的参数值 String username = req.getParameter("username"); System.out.println("username="+username); }
-
-
解决乱码
-
get方式乱码
-
tomcat7及以前版本,内部使用的字符集是ISO-8859-1,传入中文会出现乱码
-
Maven的Tomcat插件(最高支持到tomcat7)
-
在引入插件的时候设置属性
<uriEncoding>UTF-8</uriEncoding>
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); System.out.println(username); }
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cYvLCB2G-1678948129129)(C:\Users\111\AppData\Roaming\Typora\typora-user-images\image-20230316103150258.png)]
-
本地Tomcat
-
可以进行手动转换
String str=new String(username.getBytes("ISO-8859-1"), "UTF-8")
-
tomcat7以后支持中文
-
-
-
post方式乱码
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //设置流的字符集 req.setCharacterEncoding("utf-8"); BufferedReader reader = req.getReader(); String line; while ((line= reader.readLine())!=null){ System.out.println(line); }
-
-
请求转发
- 请求只转发一次
- 不能写虚拟目录
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //请求转发 req.getRequestDispatcher("/servlet01").forward(req,resp); }
-
可以使用request传递对象数据
-
是一个域对象(具备某个作用范围的对象)
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //添加 req.setAttribute("str","Attribute"); //请求转发 req.getRequestDispatcher("/servlet01").forward(req,resp); } public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { //获取指定属性 Object attribute = servletRequest.getAttribute("str"); System.out.println(attribute.toString()); } public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { //删除指定属性 servletRequest.removeAttribute("str"); }
-