ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。
由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。
1.利用ServletContext解决中文乱码问题
如果使用ServletConfig来解决,那么每一个Servlet都需要配置一份
所以我们使用全局初始化参数,只需要一份就可以解决
新建TestServlet,获取ServletContext对象,获取参数encoding的值
@WebServlet(name = "TestServlet",urlPatterns = "/poem2")
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();//获取ServletContext对象
String encoding = context.getInitParameter("encoding");//获取encoding全局参数的值
response.setContentType("text/html;charset=" + encoding);//设置编码格式
PrintWriter writer = response.getWriter();//输出到网页
writer.println("百日依山尽</br>");
writer.println("黄河入海流");
String uname = context.getInitParameter("uname");
writer.println(uname);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
结果输出:
2.多个Servlet通过ServletContext对象实现数据共享。
新建一个User类,准备存入ServletContext对象中
public class User {// 新建User类
private String name;
private int id;
private String passwd;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
新建TestContextServlet ,新建User对象并存入ServletContext对象中
public class TestContextServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = new User();
user.setId(1);
user.setName("zhangsan");
user.setPasswd("123");
ServletContext context = this.getServletContext();
context.setAttribute("user", user);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
新建TestContextServlet2,获取ServletContex中存的User对象,并输出至网页
@WebServlet(name = "TestContextServlet2",urlPatterns = "/TestContextServlet2")
public class TestContextServlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
User user = (User) context.getAttribute("user");
response.getWriter().println(user.getId()+"\t"+user.getName()+"\t"+user.getPasswd());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
结果:
注意:如果直接访问TestContextServlet2会报错