ServletContext:
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
作用:共享数据---->我们在这个servlet保存的数据可以在另外一个servlet中拿到:
public class Helloservlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Hello,servlet"); //this.getInitParameter()初始化参数 //this.getServletConfig()servlet配置 //this.getServletContext()servlet上下文 ServletContext context=this.getServletContext(); String username="java_小白";//数据 context.setAttribute("username",username);//将一个数据保存在了servletContext中,名字为:username = 值为 username } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
我们在helloservlet中创建了一个ServletContext对象,通过ServletContext的setAttribute方法,把一个数据(username)放入了这个对象之中;用于被公共取用
public class Getservlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context1=this.getServletContext(); String username =(String) context1.getAttribute("username"); resp.setContentType("text/hrml"); resp.setCharacterEncoding("utf-8"); resp.getWriter().print("名字:"+username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
我们继续在Getservlet中创建了一个ServletContext对象,不同的是我们使用了ServletContext的getAttribute方法;用于拿到username中的值,并且将它输出来
值得注意的是,这个时候的返回值是object类,所以在我们知道返回值是String类型的时候我们可以将它强制转换为String,才不发生错误
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="3.1" metadata-complete="true"> <servlet> <servlet-name>hello</servlet-name> <servlet-class>top.lostyou.servlet.Helloservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>getc</servlet-name> <servlet-class>top.lostyou.servlet.Getservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>getc</servlet-name> <url-pattern>/getc</url-pattern> </servlet-mapping> </web-app>
我们在编辑好了servlet后,每编辑好一个我们都要取对应的XML中注册
分别是 servlet 和 servlet-mapping 两个
resp.setContentType("text/hrml"); resp.setCharacterEncoding("utf-8");标签:username,java,String,ServletException,resp,ServletContext,servlet From: https://www.cnblogs.com/5ran2yl/p/16834151.html
以上两个代码是用于处理servlet的乱码问题的,比如:中文输出为????