自学Servlet_2_servletContext
1.两种获取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);