1.作用:域对象的作用:让servlet与Servlet对象可以传递数据。
2.域对象的方法:
1.setAttribute(key,value) 往域添加数据
2.getAttribute(key), 获取域对象的参数
3. removeAttribute(key) 删除域对象的参数。
3.设置参数:
public class SetAttributeServlet_04 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
//往域对象存储数据
context.setAttribute("user", "狗娃");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
4.获取参数:
public class GetAttributeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//得倒ServletContext
ServletContext context = this.getServletContext();
//从ServletContext中获取数据
String userName = (String) context.getAttribute("user");
System.out.println("姓名:"+ userName);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ServletContext域对象
猜你喜欢
转载自blog.csdn.net/chenzuen113113/article/details/80918997
今日推荐
周排行