ServletContext 获取全局配置参数

ServletContext 获取全局配置参数_第1张图片

ServletContext01:

package com.yuming.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletContext01
 */
public class ServletContext01 extends HttpServlet {
	

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1. 获取对象
		ServletContext Context = getServletContext();
		String Parameter = Context.getInitParameter("address");
		System.out.println("ServletContext01中的Parameter="+Parameter);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


ServletContext02:

package com.yuming.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletContext02
 */
public class ServletContext02 extends HttpServlet {
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1. 获取对象
		ServletContext Context = getServletContext();
		String Parameter = Context.getInitParameter("address");
		System.out.println("ServletContext02中的Parameter="+Parameter);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

web.xml:

 



	ServletContext01
	
		index.html
		index.htm
		index.jsp
		default.html
		default.htm
		default.jsp
	

	
	
		address
		北京
	

	
		
		ServletContext01
		ServletContext01
		com.yuming.servlet.ServletContext01
	
	
		ServletContext01
		/ServletContext01
	
	
		
		ServletContext02
		ServletContext02
		com.yuming.servlet.ServletContext02
	
	
		ServletContext02
		/ServletContext02
	

运行结果:

http://localhost:8081/ServletContext01/ServletContext01

http://localhost:8081/ServletContext01/ServletContext02
ServletContext 获取全局配置参数_第2张图片

你可能感兴趣的:(Servlet)