2022.5.7 Servlet 类

4.2、Servlet 类

4.2.1、Servlet 类的继承体系

4.2.2、ServletConfig 类

ServletConfig 类从类名上来看,就知道是 Servlet 程序的配置信息类。

Servlet 程序和 ServletConfig 对象都是由 Tomcat 负责创建,我们负责使用。

Servlet 程序默认是第一次访问的时候创建,ServletConfig 是每个 Servlet 程序创建时,就创建一个对应的 ServletConfig对象。

ServletConfig 类的三大作用

  • 可以获取 Servlet 程序的别名(servlet-name)的值

  • 获取初始化参数 init-param

  • 获取 ServletContext 对象

案例1

HelloServlet

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.*;
 4  import java.io.IOException;
 5  6  public class HelloServlet implements Servlet {
 7  8      @Override
 9      public void init(ServletConfig servletConfig) throws ServletException {
10 11          //1、可以获取Servlet程序的别名servlet-name的值
12          System.out.println("HelloServlet程序的别名是:" + servletConfig.getServletName());
13          //2、获取初始化参数init-param   获取参数名是username的参数值
14          System.out.println("初始化参数username的值是;" + servletConfig.getInitParameter("username"));
15          System.out.println("初始化参数url的值是;" + servletConfig.getInitParameter("url"));
16          //3、获取ServletContext对象
17          System.out.println(servletConfig.getServletContext());
18      }
19 20      @Override
21      public ServletConfig getServletConfig() {
22          return null;
23      }
24 25      @Override
26      public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
27 28      }
29 30      @Override
31      public String getServletInfo() {
32          return null;
33      }
34 35      @Override
36      public void destroy() {
37 38      }
39  }
复制代码

web.xml

复制代码
 1  <?xml version="1.0" encoding="UTF-8"?>
 2  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5           version="4.0">
 6      <servlet>
 7          <servlet-name>HelloServlet</servlet-name>
 8          <servlet-class>com.xing.servlet.HelloServlet</servlet-class>
 9 10          <!--init-param是初始化参数  相当于map-->
11          <init-param>
12              <!--是参数名-->
13              <param-name>username</param-name>
14              <!--是参数值-->
15              <param-value>root</param-value>
16          </init-param>
17 18          <init-param>
19              <param-name>url</param-name>
20              <param-value>jdbc:mysql://localhost:3306/test</param-value>
21          </init-param>
22      </servlet>
23 24      <servlet-mapping>
25          <servlet-name>HelloServlet</servlet-name>
26          <url-pattern>/hello</url-pattern>
27      </servlet-mapping>
28  </web-app>
复制代码

访问http://localhost:8080/06_servlet/hello

案例二:

HelloServlet2

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.ServletConfig;
 4  import javax.servlet.ServletException;
 5  import javax.servlet.http.HttpServlet;
 6  import javax.servlet.http.HttpServletRequest;
 7  import javax.servlet.http.HttpServletResponse;
 8  import java.io.IOException;
 9 10  public class HelloServlet2 extends HttpServlet {
11 12      @Override
13      public void init(ServletConfig config) throws ServletException {
14          //如果重写了init方法 那么一定要调用super.init(config) 否则在调用初始化参数时会报空指针
15          // 父类GenericServlet中也有init方法
16          //如果子类重写了init方法,那么初始化时就会调用子类的init方法,这个赋值(this.config = config)操作就会失效,就会获取不到配置信息
17          super.init(config);
18          System.out.println("重写了init初始化方法,做了一些工作");
19      }
20 21      @Override
22      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
23 24          // getServletConfig()是父类GenericServlet中的方法,返回配置类(xml中配置信息)
25          ServletConfig servletConfig = getServletConfig();
26          System.out.println(servletConfig);
27 28          //获取初始化参数init-param
29          System.out.println("初始化参数username的值是;" + servletConfig.getInitParameter("username"));
30          System.out.println("初始化参数url的值是;" + servletConfig.getInitParameter("url"));
31 32      }
33 34      @Override
35      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
36          System.out.println("HelloServlet2 的doPost方法");
37      }
38  }
复制代码

web.xml

复制代码
 1  <?xml version="1.0" encoding="UTF-8"?>
 2  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5           version="4.0">
 6  7  8      <servlet>
 9          <servlet-name>HelloServlet2</servlet-name>
10          <servlet-class>com.xing.servlet.HelloServlet2</servlet-class>
11 12          <init-param>
13              <param-name>username</param-name>
14              <param-value>root2</param-value>
15          </init-param>
16          <init-param>
17              <param-name>url</param-name>
18              <param-value>jdbc:mysql://localhost:3306/test2</param-value>
19          </init-param>
20 21      </servlet>
22 23      <servlet-mapping>
24          <servlet-name>HelloServlet2</servlet-name>
25          <url-pattern>/hello2</url-pattern>
26      </servlet-mapping>
27 28  </web-app>
复制代码

访问http://localhost:8080/06_servlet/hello2 浏览器默认走get请求

复制代码
 1  //GenericServlet中得源码
 2  3  private transient ServletConfig config;
 4  5  public void init(ServletConfig config) throws ServletException {
 6      //将config的值保存到this.config
 7      this.config = config;
 8      this.init();
 9  }
10 11  public ServletConfig getServletConfig() {
12      return config;
13  }
14 15  //如果子类重写了init方法,那么初始化时就会调用子类的init方法,这个赋值(this.config = config)操作就会失效,就会获取不到配置信息
复制代码

4.2.3、ServletContext 类

什么是 ServletContext?

  • ServletContext 是一个接口(interface),它表示 Servlet 上下文对象

  • 一个 web 工程,只有一个 ServletContext 对象实例。

  • ServletContext 对象是一个域对象。

  • ServletContext 是在 web 工程部署启动的时候创建。在 web 工程停止的时候销毁。

什么是域对象?

域对象,是可以像 Map 一样存取数据的对象,叫域对象。

这里的域指的是存取数据的操作范围(整个 web 工程)。

 存数据取数据删除数据
Map put() get() remove()
域对象 setAttribute() getAttribute() removeAttribute()

ServletContext 类的四个作用

  • 获取 web.xml 中配置的上下文参数 context-param

  • 获取当前的工程路径,格式: /工程路径

  • 获取工程部署后在服务器硬盘上的绝对路径

  • 像 Map一样存取数据

ContextServlet

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.ServletContext;
 4  import javax.servlet.ServletException;
 5  import javax.servlet.http.HttpServlet;
 6  import javax.servlet.http.HttpServletRequest;
 7  import javax.servlet.http.HttpServletResponse;
 8  import java.io.IOException;
 9 10  public class ContextServlet extends HttpServlet {
11      @Override
12      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13 14      }
15 16      @Override
17      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18          //1、获取web.xml中配置的上下文参数context-param  不能获取init-param
19          //getServletConfig得到配置类  getServletContext得到配置类中的上下文参数类
20          ServletContext context = getServletConfig().getServletContext();
21          // ServletContext context = getServletContext();  还可以直接这么获取ServletContext
22          
23          String username = context.getInitParameter("username");
24          System.out.println("context-param参数username的值是:" + username);//root
25          System.out.println("context-param参数password的值是:" + context.getInitParameter("password"));//123456
26          //2、获取当前的工程路径,格式: /工程路径
27          System.out.println( "当前工程路径:" + context.getContextPath());// /06_servlet
28 29          //3、获取工程部署后在服务器硬盘上的绝对路径
30 31          //  /(斜杠)表示服务器解析地址为:http://ip:port/工程名/   得到项目部署的真实路径(服务器解析地址到部署路径的映射)
32          System.out.println("工程部署的路径是:" + context.getRealPath("/"));//D:\Study\资料\06-Servlet-1\代码\06_servlet\out\artifacts\06_servlet_Web_exploded\
33                                                                            //这个目录下的内容就是idea web目录下的内容   还有一些额外的编译文件
34          System.out.println("工程下css目录的绝对路径是:" + context.getRealPath("/css"));
35          System.out.println("工程下imgs目录1.jpg的绝对路径是:" + context.getRealPath("/imgs/1.jpg"));
36      }
37  }
复制代码

web.xml

复制代码
 1  <?xml version="1.0" encoding="UTF-8"?>
 2  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5           version="4.0">
 6  7      <!--context-param是上下文参数(它属于整个web工程)-->
 8      <context-param>
 9          <param-name>username</param-name>
10          <param-value>root</param-value>
11      </context-param>
12        <!--context-param是上下文参数(它属于整个web工程)-->
13      <context-param>
14          <param-name>password</param-name>
15          <param-value>123456</param-value>
16      </context-param>
17 18      <servlet>
19          <servlet-name>ContextServlet</servlet-name>
20          <servlet-class>com.xing.servlet.ContextServlet</servlet-class>
21      </servlet>
22      <servlet-mapping>
23          <servlet-name>ContextServlet</servlet-name>
24          <url-pattern>/contextServlet</url-pattern>
25      </servlet-mapping>
26 27  </web-app>
复制代码

像 Map 一样存取数据:

我在这个Servlet中保存的数据,可以在另外一个servlet中拿到

ContextServlet1

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.ServletContext;
 4  import javax.servlet.ServletException;
 5  import javax.servlet.http.HttpServlet;
 6  import javax.servlet.http.HttpServletRequest;
 7  import javax.servlet.http.HttpServletResponse;
 8  import java.io.IOException;
 9 10  public class ContextServlet1 extends HttpServlet {
11 12      @Override
13      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
14          // 获取ServletContext对象
15          ServletContext context = getServletContext();
16          System.out.println(context);
17          System.out.println("保存之前: Context1 获取 key1的值是:"+ context.getAttribute("key1"));//保存之前: Context1 获取 key1的值是:null
18 19          context.setAttribute("key1", "小明");
20          System.out.println("Context1 中获取域数据key1的值是:"+ context.getAttribute("key1"));//Context1 中获取域数据key1的值是:小明
21      }
22  }
复制代码

ContextServlet2

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.ServletContext;
 4  import javax.servlet.ServletException;
 5  import javax.servlet.http.HttpServlet;
 6  import javax.servlet.http.HttpServletRequest;
 7  import javax.servlet.http.HttpServletResponse;
 8  import java.io.IOException;
 9 10  public class ContextServlet2 extends HttpServlet {
11      @Override
12      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13          ServletContext context = getServletContext();
14          System.out.println(context);
15          System.out.println("Context2 中获取域数据key1的值是:"+ context.getAttribute("key1"));
16      }
17  }
复制代码

web.xml

复制代码
 1  <?xml version="1.0" encoding="UTF-8"?>
 2  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5           version="4.0">
 6      <servlet>
 7          <servlet-name>ContextServlet1</servlet-name>
 8          <servlet-class>com.xing.servlet.ContextServlet1</servlet-class>
 9      </servlet>
10      <servlet-mapping>
11          <servlet-name>ContextServlet1</servlet-name>
12          <url-pattern>/context1</url-pattern>
13      </servlet-mapping>
14      
15      <servlet>
16          <servlet-name>ContextServlet2</servlet-name>
17          <servlet-class>com.xing.servlet.ContextServlet2</servlet-class>
18      </servlet>
19      <servlet-mapping>
20          <servlet-name>ContextServlet2</servlet-name>
21          <url-pattern>/context2</url-pattern>
22      </servlet-mapping>
23 24  </web-app>
复制代码

访问: localhost:8080/06_servlet/context1

访问: localhost:8080/06_servlet/context2 也能访问到key1的value值

因为一个 web 工程,只有一个 ServletContext 对象,所有servlet程序共用一个,ServletContext 是在 web 工程部署启动的时候创建。在 web 工程停止的时候销毁。

读取资源文件

Properties

  • 在java目录下新建properties。

1  username=root
2  password=123456
  • 在resources目录下新建properties

执行后发现:都被打包到了同一个路径下:classes,我们俗称这个路径为类路径classpath

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.ServletException;
 4  import javax.servlet.http.HttpServlet;
 5  import javax.servlet.http.HttpServletRequest;
 6  import javax.servlet.http.HttpServletResponse;
 7  import java.io.IOException;
 8  import java.io.InputStream;
 9  import java.util.Properties;
10 11  public class ServletDemo01 extends HttpServlet {
12      @Override
13      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
14          //                       将资源变成流    /代表当前web项目:servlet-02-1.0-SNAPSHOT文件夹
15          InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
16          Properties properties = new Properties();
17          properties.load(is);
18          //                       获取属性
19          String user = properties.getProperty("username");
20          String pwd = properties.getProperty("password");
21 22          resp.getWriter().print(user+":"+pwd);//写到前端
23      }
24 25      @Override
26      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
27          doGet(req, resp);
28      }
29  }
复制代码

web.xml

复制代码
 1  <?xml version="1.0" encoding="UTF-8"?>
 2  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
 5                        http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 6           version="4.0"
 7           metadata-complete="true">
 8      <servlet>
 9          <servlet-name>d1</servlet-name>
10          <servlet-class>com.xing.servlet.ServletDemo01</servlet-class>
11      </servlet>
12 13      <servlet-mapping>
14          <servlet-name>d1</servlet-name>
15          <url-pattern>/d1</url-pattern>
16      </servlet-mapping>
17  </web-app>
复制代码

4.2.4、HttpServletRequest 类

HttpServletRequest 类有什么作用。

每次只要有请求进入Tomcat服务器,Tomcat服务器就会把请求过来的HTTP协议信息解析好封装到Request对象中。然后传递到service方法(doGet和doPost)中给我们使用。我们可以通过HttpServletRequest对象,获取到所有请求的信息。

HttpServletRequest 类的常用方法

  • getRequestURI() 获取请求的资源路径

  • getRequestURL() 获取请求的统一资源定位符(绝对路径)

  • getRemoteHost() 获取客户端的ip地址

  • getHeader() 获取请求头

  • getParameter() 获取请求的参数

  • getParameterValues() 获取请求的参数(多个值的时候使用)

  • getMethod() 获取请求的方式GET或POST

  • setAttribute(key, value); 设置域数据

  • getAttribute(key); 获取域数据

  • getRequestDispatcher() 获取请求转发对象

RequestAPIServlet

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.ServletException;
 4  import javax.servlet.http.HttpServlet;
 5  import javax.servlet.http.HttpServletRequest;
 6  import javax.servlet.http.HttpServletResponse;
 7  import java.io.IOException;
 8  9  public class RequestAPIServlet extends HttpServlet {
10 11      @Override
12      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
13          //getRequestURI()获取请求的资源路径
14          System.out.println("URI => " + req.getRequestURI());//URI => /07_servlet/requestAPIServlet
15 16          //getRequestURL()获取请求的统一资源定位符(绝对路径)
17          System.out.println("URL => " + req.getRequestURL());//URL => http://localhost:8080/07_servlet/requestAPIServlet
18 19          //getRemoteHost()获取客户端(发起请求的)的ip地址                                              127.0.0.1  是ipv4的本机ip
20          System.out.println("客户端 ip地址 => " + req.getRemoteHost());//客户端 ip地址 => 0:0:0:0:0:0:0:1  我的本机返回的ipv6的本地ip
21 22          //getHeader()获取请求头
23          System.out.println("请求头User-Agent ==>> " + req.getHeader("User-Agent"));
24 25          //getMethod()获取请求的方式GET或POST
26          System.out.println( "请求的方式 ==>> " + req.getMethod() );//请求的方式 ==>> GET
27      }
28  }
复制代码

web.xml

复制代码
 1  <?xml version="1.0" encoding="UTF-8"?>
 2  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5           version="4.0">
 6  7      <servlet>
 8          <servlet-name>RequestAPIServlet</servlet-name>
 9          <servlet-class>com.xing.servlet.RequestAPIServlet</servlet-class>
10      </servlet>
11      <servlet-mapping>
12          <servlet-name>RequestAPIServlet</servlet-name>
13          <url-pattern>/requestAPIServlet</url-pattern>
14      </servlet-mapping>
15 16  </web-app>
复制代码

访问 localhost:8080/07_servlet/requestAPIServlet

如何获取请求参数

表单:form.html

复制代码
 1  <!DOCTYPE html>
 2  <html lang="zh_CN">
 3  <head>
 4      <meta charset="UTF-8">
 5      <title>Title</title>
 6  </head>
 7  <body>
 8      <form action="http://localhost:8080/07_servlet/parameterServlet" method="get">
 9          用户名:<input type="text" name="username"><br/>
10          密码:<input type="password" name="password"><br/>
11          兴趣爱好:<input type="checkbox" name="hobby" value="cpp">C++
12          <input type="checkbox" name="hobby" value="java">Java
13          <input type="checkbox" name="hobby" value="js">JavaScript<br/>
14          <input type="submit">
15      </form>
16  </body>
17  </html>
复制代码

ParameterServlet

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.ServletException;
 4  import javax.servlet.http.HttpServlet;
 5  import javax.servlet.http.HttpServletRequest;
 6  import javax.servlet.http.HttpServletResponse;
 7  import java.io.IOException;
 8  import java.util.Arrays;
 9 10  public class ParameterServlet extends HttpServlet {
11 12      @Override
13      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
14 15          // 获取请求参数                    表单中name=username的参数
16          String username = req.getParameter("username");
17          String password = req.getParameter("password");
18          String[] hobby = req.getParameterValues("hobby");
19 20          System.out.println("用户名:" + username);//用户名:小明
21          System.out.println("密码:" + password);//密码:123456
22          System.out.println("兴趣爱好:" + Arrays.asList(hobby));//兴趣爱好:[java, js]
23      }
24 25      @Override
26      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
27     
28      }
29  }
30  
复制代码

web.xml

复制代码
 1  <?xml version="1.0" encoding="UTF-8"?>
 2  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5           version="4.0">
 6  7      <servlet>
 8          <servlet-name>ParameterServlet</servlet-name>
 9          <servlet-class>com.xing.servlet.ParameterServlet</servlet-class>
10      </servlet>
11      <servlet-mapping>
12          <servlet-name>ParameterServlet</servlet-name>
13          <url-pattern>/parameterServlet</url-pattern>
14      </servlet-mapping>
15 16  </web-app>
复制代码

访问 http://localhost:8080/07_servlet/form.html 输入信息 点击提交

当请求是get请求时,用户名可以输入中文,且在后台输出不乱码,当请求是post请求时,用户名输入中文,后台输出乱码,需要设置字符集

表单:form.html

复制代码
 1  <!DOCTYPE html>
 2  <html lang="zh_CN">
 3  <head>
 4      <meta charset="UTF-8">
 5      <title>Title</title>
 6  </head>
 7  <body>
 8      <form action="http://localhost:8080/07_servlet/parameterServlet" method="post">
 9          用户名:<input type="text" name="username"><br/>
10          密码:<input type="password" name="password"><br/>
11          兴趣爱好:<input type="checkbox" name="hobby" value="cpp">C++
12          <input type="checkbox" name="hobby" value="java">Java
13          <input type="checkbox" name="hobby" value="js">JavaScript<br/>
14          <input type="submit">
15      </form>
16  </body>
17  </html>
复制代码

ParameterServlet

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.ServletException;
 4  import javax.servlet.http.HttpServlet;
 5  import javax.servlet.http.HttpServletRequest;
 6  import javax.servlet.http.HttpServletResponse;
 7  import java.io.IOException;
 8  import java.util.Arrays;
 9 10  public class ParameterServlet extends HttpServlet {
11 12      @Override
13      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
14 15      }
16 17      @Override
18      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
19          // 设置请求体的字符集为UTF-8,从而解决post请求的中文乱码问题
20          // 在获取请求参数之前调用才有效(这行代码必须写在请求参数代码的前面)   
21          req.setCharacterEncoding("UTF-8");
22 23          String username = req.getParameter("username");
24          String password = req.getParameter("password");
25          String[] hobby = req.getParameterValues("hobby");
26 27          System.out.println("用户名:" + username);//用户名:小明
28          System.out.println("密码:" + password);//密码:123456
29          System.out.println("兴趣爱好:" + Arrays.asList(hobby));//兴趣爱好:[cpp, java, js]
30      }
31  }
复制代码

web.xml

复制代码
 1  <?xml version="1.0" encoding="UTF-8"?>
 2  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5           version="4.0">
 6  7      <servlet>
 8          <servlet-name>ParameterServlet</servlet-name>
 9          <servlet-class>com.xing.servlet.ParameterServlet</servlet-class>
10      </servlet>
11      <servlet-mapping>
12          <servlet-name>ParameterServlet</servlet-name>
13          <url-pattern>/parameterServlet</url-pattern>
14      </servlet-mapping>
15 16  </web-app>
复制代码

访问 http://localhost:8080/07_servlet/form.html 输入信息 点击提交

4.2.5、HttpServletResponse 类

HttpServletResponse 类的作用

HttpServletResponse类和HttpServletRequest类一样。每次请求进来,Tomcat服务器都会创建一个Response对象传递给Servlet程序去使用。HttpServletRequest表示请求过来的信息,HttpServletResponse表示所有响应的信息,

我们如果需要设置返回给客户端的信息,都可以通过HttpServletResponse对象来进行设置

两个输出流的说明。

  • 字节流 getOutputStream(); 常用于下载(传递二进制数据)

  • 字符流 getWriter(); 常用于回传字符串(常用)

  • 两个流同时只能使用一个,使用了字节流,就不能再使用字符流,反之亦然,否则就会报错。

如何往客户端回传数据

要求: 往客户端回传字符串数据。

ResponseIOServlet

复制代码
 1  package com.xing.servlet;
 2  3  import javax.servlet.ServletException;
 4  import javax.servlet.http.HttpServlet;
 5  import javax.servlet.http.HttpServletRequest;
 6  import javax.servlet.http.HttpServletResponse;
 7  import java.io.IOException;
 8  import java.io.PrintWriter;
 9 10  public class ResponseIOServlet extends HttpServlet {
11      @Override
12      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
13          //resp.getCharacterEncoding()  获取响应字符集
14          System.out.println( resp.getCharacterEncoding() );//默认ISO-8859-1  这个字符集不支持中文
15 16          //解决响应中文乱码问题   法一   
17          // resp.setCharacterEncoding("UTF-8");//设置服务器字符集为UTF-8
18          // resp.setHeader("Content-Type", "text/html; charset=UTF-8");//通过响应头,设置浏览器也使用UTF-8字符集    参数形式类似map   将Content-Type设置为text/html; charset=UTF-8
19          
20          //解决响应中文乱码问题   法二 
21          // 它会同时设置服务器和客户端都使用UTF-8字符集,还设置了响应头
22          // 此方法一定要在获取流对象之前调用才有效
23          resp.setContentType("text/html; charset=UTF-8");
24          
25          //要求 : 往客户端回传 字符串 数据。
26          PrintWriter writer = resp.getWriter();
27          writer.write("response 你好");
28      }
29  }
复制代码

web.xml

复制代码
 1  <?xml version="1.0" encoding="UTF-8"?>
 2  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5           version="4.0">
 6  7      <servlet>
 8          <servlet-name>ResponseIOServlet</servlet-name>
 9          <servlet-class>com.xing.servlet.ResponseIOServlet</servlet-class>
10      </servlet>
11      <servlet-mapping>
12          <servlet-name>ResponseIOServlet</servlet-name>
13          <url-pattern>/responseIOServlet</url-pattern>
14      </servlet-mapping>
15 16  </web-app>
复制代码

访问: localhost:8080/07_servlet/responseIOServlet

 
posted @   暴躁C语言  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示