java-web servletContext共享数据
servletContext共享数据
web容器在启动的时候,它会为每个web程序都创建一个对应的servletContext,它代表了当前的web程序。
1.在某个servlet中保存数据
package com.changfan.servlet1; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); //存放变量 context.setAttribute("userName","changfan"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
2.在另一个servlet中读取数据
package com.changfan.servlet1; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class Getc extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String userName = (String) context.getAttribute("userName"); PrintWriter writer = resp.getWriter(); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html"); writer.println("用户名:"+userName); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
非学无以广才,非志无以成学。
正是因为今天的不完美,才对未来充满希望。
----长帆