通过application获取资源,它的根路径是WebContent,它可以获取web-inf下的资源
通过getclassload()获取资源,它的根路径是classes,不能获取web-inf下的资源
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TestServletContext</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>username</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>123123</param-value>
</context-param>
<servlet>
<description></description>
<display-name>TestContext01</display-name>
<servlet-name>TestContext01</servlet-name>
<servlet-class>com.cdsxt.context.TestContext01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestContext01</servlet-name>
<url-pattern>/context01</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>TestContext02</display-name>
<servlet-name>TestContext02</servlet-name>
<servlet-class>com.cdsxt.context.TestContext02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestContext02</servlet-name>
<url-pattern>/context02</url-pattern>
</servlet-mapping>
</web-app>
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletContext application = this.getServletContext();
String username = application.getInitParameter("username");
String password = application.getInitParameter("password");
System.out.println(username);
System.out.println(password);
System.out.println("--------");
application.setAttribute("username", "lisi");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
/**
* 获取ServletContext application
*
* ServletConfig.getServletContext()
* this.getServletContext();
* 不宜放大量数据
*
*
*/
System.out.println(this.getServletContext().getAttribute("username"));
//关于得到项目路径里面的文件
//有ServletContext对象去得到文件的路径
ServletContext context = this.getServletContext();
//得到系统文件
System.out.println(context.getResourceAsStream("WEB-INF/web.xml"));
System.out.println(context.getResource("WEB-INF/web.xml").getPath());
System.out.println(context.getRealPath("WEB-INF/web.xml"));
Set<String> path = context.getResourcePaths("/WEB-INF/");
for(String p:path){
System.out.println(p);
}
}