Servlet servletContext objects

ServletContext

Servlet context. Environment after the container starts, only one.

ServletContext methods

1.getInitParameterNames ();
Get the name of the context parameter values of all web.xml file returns an enumeration. Can target specific name with getInitParameter (), returns a specific value.

ServletContext servletContext =   servletConfig.getServletContext();
Enumeration<String> names= servletContext.getInitParameterNames();
		
		while(names.hasMoreElements()){
			String name= names.nextElement();
			String value = servletContext.getInitParameter(name);
			System.out.println(name+"="+value);
		}

2.getAttribute, setAttribute
set and retrieve data from the specified fields in the attribute space servletContext.

servletContext.setAttribute("email", "1234567");
		servletContext.setAttribute("name", "吗啡");
		
		String name = (String) servletContext.getAttribute("name");
		System.out.println(name);

3.getRealPath, getRealPath
getRealPath: Get the current web application specified file or path to the local file system, is based on the path of the letter.
getRealPath: Gets the name of the current web container

		String realPath = servletContext.getRealPath("/images");
		System.out.println(realPath);
		System.out.println("ee");
		System.out.println(servletContext.getContextPath());

consolse

D:\javaWeb\Servlet\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ServletLifeTime\images
ee
/ServletLifeTime
Published 114 original articles · won praise 8 · views 5496

Guess you like

Origin blog.csdn.net/OVO_LQ_Start/article/details/104696165