1.两种获取servletContext对象的方式
2.用context对象实现数据共享
3.获取ServletContext的共享数据
4.通过servletContext,获取为web应用配置的初始化参数
5.通过servletContext获取文件的mime类型
6.通过servletContext 实现请求转发
ServletContext context = this.getServletConfig().getServletContext();
ServletContext context1 = this.getServletContext();2.用context对象实现数据共享
context.setAttribute("data", "aaaaaaaaaa");3.获取ServletContext的共享数据
context.getAttribute("data")4.通过servletContext,获取为web应用配置的初始化参数
String url = this.getServletContext().getInitParameter("url");
String username = this.getServletContext().getInitParameter("username");
String password = this.getServletContext().getInitParameter("password"); <context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>root</param-value>
</context-param>5.通过servletContext获取文件的mime类型
String filename = "1.jpg";
ServletContext context = this.getServletContext();
System.out.println(context.getMimeType(filename));6.通过servletContext 实现请求转发
//servlet收到请求产生数据,然后转交给jsp显示
String data = "aaaaaa";
this.getServletContext().setAttribute("data", data);
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/view.jsp");
rd.forward(request, response);
本文深入探讨了如何使用ServletContext对象在Web应用中实现数据共享,并展示了如何通过配置文件设置初始化参数,以及如何通过ServletContext获取文件的MIME类型和文件路径。同时,介绍了ServletContext如何实现请求转发,将数据从Servlet传递到JSP页面展示。
802

被折叠的 条评论
为什么被折叠?



