欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WEB-ServletConfig与ServletContext

程序员文章站 2022-05-08 13:29:40
...
import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class HelloServlet implements Servlet {
	private ServletConfig servletConfig;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		this.servletConfig = arg0;
	}

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("hello");
		String initParameter = servletConfig.getInitParameter("encode");
		System.out.println("initParameter:"+initParameter);
		ServletContext servletContext = servletConfig.getServletContext();
		System.out.println("servletContext:"+servletContext);
		String servletName = servletConfig.getServletName();
		System.out.println("servletName:"+servletName);
		
		String initParameter2 = servletContext.getInitParameter("age");
		System.out.println("initParameter2:"+initParameter2);
		String realPath = servletContext.getRealPath("login.htli");
		System.out.println("realPath:"+realPath);
		
		
	}

}

<?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" 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">
 	<!-- 
 		注册
 			1.加载类全路径
 			2.url
 			
 			
 		两个<servlet-name>名字需要对应好,一般为Servlet的文件名
 	 -->
 	 <context-param>
 	 	<param-name>age</param-name>
 	 	<param-value>18</param-value>
 	 </context-param>
 	 <servlet>
 	 	<servlet-name>HelloServlet</servlet-name>
 	 	<servlet-class>com.atguigu.servlet.HelloServlet</servlet-class>
 	 	
 	 	<init-param>
 	 		<param-name>encode</param-name>
 	 		<param-value>UTF-8</param-value>
 	 	</init-param>	
 	 	
 	 </servlet>
 	 <servlet-mapping>
 	 	<servlet-name>HelloServlet</servlet-name>
 	 	<url-pattern>/HelloServlet</url-pattern>
 	 </servlet-mapping>
</web-app>