ServletContext

107 阅读1分钟

作用

  • 可以让servlet之间共享数据
  • 获取web应用的初始化参数
  • 请求转发
  • 读取资源文件

可以让servlet之间共享数据

public class setContext extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String value = "beautiful";
        context.setAttribute("val",value);
    }
}


public class getContext extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String value = (String)context.getAttribute("val");
        PrintWriter out = resp.getWriter();
        out.println(value);
    }
}

需要先请求(执行)含有context.setAttribute("val",value)的servlet。之后context中才有值。

获取web应用的初始化参数

public class getParameter extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String s = context.getInitParameter("url");
        resp.getWriter().println(s);
    }
}

web.xml加入如下属性

<!--  web应用初始化参数  -->
<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:8080/baidu</param-value>
  </context-param>

请求转发

public class reqForward extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/getP");
        //需要转发到的servlet的url路径(在web.xml中配置的)
        requestDispatcher.forward(req,resp);
    }
}

读取资源文件

public class getProperties extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        InputStream in = context.getResourceAsStream("/WEB-INF/classes/test.properties");//需要在target目录下
        Properties properties = new Properties();
        properties.load(in);
        String username = (String) properties.get("username");
        String password= (String) properties.get("password");
        resp.getWriter().println(username+":"+password);
    }
}
username=kittyguy
password=123456

要想maven获取资源,需要在pom.xml中配置

<build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
</build>