ServletContext

Web容器启动的时候, 它会为每个web程序创建一个ServletContext的对象, 它代表了当前的web应用.

作用为:

共享数据

我在这个Servlet中保存的数据, 可以在另一个servlet中拿到, 凌驾于所有servlet之上的

首先在一个Servelt程序中设置servletContext的值:

1
2
3
4
5
6
7
8
9
public class HelloServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = "lxb";
context.setAttribute("username", username);
}
}

再编写一个Servlet程序, 将值取出并打印在浏览器中:

1
2
3
4
5
6
7
8
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
resp.getWriter().println("名字" + username);
}
}

首先执行第一个程序, 将值放入, 然后再执行第二个把值取出. 输出结果为:

下面来解决乱码问题, 设置一下响应格式就可以了:

1
2
3
4
5
6
7
8
9
10
11
12
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");

resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");

resp.getWriter().println("名字" + username);
}
}

输出为:

获取初始化参数

在web.xml中设置一个初始化的参数

1
2
3
4
<context-param>
<param-name>url</param-name>
<param-value>jdbc:maysql://localhost:3306</param-value>
</context-param>

然后新建一个servlet程序对参数进行读取即可:

1
2
3
4
5
6
7
8
public class GetParam extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().println(url);
}
}

输出为:

请求转发

使用context对象的getRequestDispatcher() 方法即可, 放入目标地址, 并调用forward() 方法, 即可实现转发

1
2
3
4
5
6
7
public class Dispacher extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.getRequestDispatcher("/getparam").forward(req, resp);
}
}

输出为:

注意地址栏, 该方法只是调用另一个servlet的页面, 不会跳转到另一个地址

这里要与重定向区分起来, 重定向是直接跳转过去

读取资源文件

Properties类

  • 在java目录下新建properties
  • 在resources目录下新建properties

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

1
2
username=root
password=123456
1
2
3
4
5
6
7
8
9
10
11
12
public class PropertiesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");

Properties properties = new Properties();
properties.load(is);
String username = properties.getProperty("username");

resp.getWriter().println(username);
}
}
-------------本文结束感谢您的阅读-------------
可以请我喝杯奶茶吗