ServletContext对象
作者:互联网
在每个web容器中,都会有一个对应的ServletContext对象,它代表着这个web应用。
利用ServletContext对象实现数据的共享,也就是说我们在一个servlet中存放的数据,可以在另外一个servlet中拿到。
1.建立数据存放的类 PutServlet
1 package com.jms.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletContext; 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public class PutServlet extends HttpServlet{ 12 13 @Override 14 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 15 16 ServletContext context = this.getServletContext();//获取这个web的ServletContext对象 17 context.setAttribute("username", "金木三");//将一个数据存放到这个ServletContext中,其中名为“username”,值为“金木三” 18 } 19 20 @Override 21 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 22 doGet(req, resp); 23 } 24 25 }
2.建立一个数据读取的类 GetServlet
1 package com.jms.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletContext; 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public class GetServlet extends HttpServlet{ 12 13 @Override 14 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 15 16 ServletContext context = this.getServletContext();//获取这个web的ServletContext对象 17 String name = (String)context.getAttribute("username");//通过名找到对应的值 18 resp.setCharacterEncoding("utf-8");//设置响应编码 19 resp.setContentType("text/html");//设置格式 20 resp.getWriter().print(name); 21 } 22 23 @Override 24 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 25 doGet(req, resp); 26 } 27 28 }
3.修改web.xml文件,添加以下内容
<!--注册Servlet--> <servlet> <servlet-name>gets</servlet-name> <servlet-class>com.jms.servlet.GetServlet</servlet-class> </servlet> <!--Servlet的请求路径--> <servlet-mapping> <servlet-name>gets</servlet-name> <url-pattern>/gets</url-pattern> </servlet-mapping> <!--注册Servlet--> <servlet> <servlet-name>puts</servlet-name> <servlet-class>com.jms.servlet.PutServlet</servlet-class> </servlet> <!--Servlet的请求路径--> <servlet-mapping> <servlet-name>puts</servlet-name> <url-pattern>/puts</url-pattern> </servlet-mapping>
4.进行测试
我们首先直接访问gets进行数据的读取,看能否读到数据
此时我们读的数据为null,因为我们还没有存放数据
那么我们尝试一下先访问puts,再访问gets尝试一下
此时成功的读取到了ServletContext中的数据
(本文仅作个人学习记录用,如有纰漏,敬请指正)
标签:ServletException,对象,resp,ServletContext,import,servlet,javax 来源: https://www.cnblogs.com/jmsstudy/p/16513862.html