Servlet--ServletContext(三)获取web.xml配置参数

Servlet--ServletContext(三)获取web.xml配置参数

一、ServletContext作用之获取配置文件参数
1、获取配置文件实例:
package test07_3context;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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

public class WebServlet extends HttpServlet {

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("=========在控制台输出Web配置信息=========");
		
		//获取ServletContext
		ServletContext app = getServletContext();
		//获取web配置的信息
		System.out.println("①、通过参数名称获取Web配置的信息");
		String names = app.getInitParameter("name");
		System.out.println("name的值:"+names);
		String ages = app.getInitParameter("age");
		System.out.println("age的值:"+ages);
		System.out.println("--------------------");
		//通过遍历方式获取web配置的信息
		System.out.println("②、通过Enumration遍历方式获取web配置的信息");
		Enumeration en = app.getInitParameterNames();
		while(en.hasMoreElements()){
			String key = en.nextElement();
			System.out.println("key的值为:"+app.getInitParameter(key));
		}
		
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("===========在网页输出Web配置信息==========="+"
"); out.println("①、通过参数名称获取Web配置的信息"+"
"); ServletContext ap = getServletContext(); String nm = ap.getInitParameter("name"); out.print("name的值:"+nm+"
"); String ag = ap.getInitParameter("age"); out.print("age的值:"+ag+"
"); out.println("②、通过Enumration遍历方式获取web配置的信息"+"
"); Enumeration eu = ap.getInitParameterNames(); while(eu.hasMoreElements()){ String ke = eu.nextElement(); out.print("key的值为:"+ap.getInitParameter(ke)+"
"); } } }
2、配置文件参数


 
 
 
 	name
 	我的家乡在中国
 
 
 	age
 	65
 
 
    This is the description of my J2EE component
    This is the display name of my J2EE component
    WebServlet
    test07_3context.WebServlet
    1
  

  
    WebServlet
    /WebServlet
  

3、测试
启动该项目,在浏览器中输入测试地址:http://127.0.0.1:8080/test07_3/WebServlet 
测试结果:
A、控制台结果:
Servlet--ServletContext(三)获取web.xml配置参数_第1张图片

B、网页端结果:
Servlet--ServletContext(三)获取web.xml配置参数_第2张图片

你可能感兴趣的:(JavaWEB,#,#)