servlet配置初始化信息

一、servlet配置初始化信息的两种方式

  • 1、ServletContext(即application)为应用上下文,代表当前应用的配置信息
  • 2、ServeltConfig代表了当前Servlet的配置信息的对象

1.1、在web.xml中设置application初始化数据


	name
	value


	TextApplication
	com.blog.servlet.AddArticleRServlet


	TextApplication
	com.blog.servlet.AddArticleRServlet

  • param-name属性:设置的是参数的名字
  • param-value属性:设置的是参数的值

1.2、在application中,获取初始化数据

在servlet中,context对象就是应用上下文对象,只是application是jsp中的内置对象,两者都是同一个概念。而servlet中的应用上下文对象,需要从request对象中获得

public class TextApplication extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String value = req.getServletContext().getInitParameter("name");
		ServletContext context = req.getServletContext();
		System.out.println("value=" + value);
}

}
打印结果:value=value

2.1、在web.xml中设置ServeltConfig初始化数据,init-param必须放servlet-class的下面


	TextApplication
	com.blog.servlet.AddArticleRServlet
	
		name
		value
	


	TextApplication
	com.blog.servlet.AddArticleRServlet

2.2、通过ServeltConfig对象,获取当前servlet页面的初始化数据

public class TextApplication extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ServletConfig servletConfig = this.getServletConfig();
		String parameter = servletConfig.getInitParameter("name");
		System.out.println("value=" + parameter);
	}
}

打印结果:value=value

注:当然web.xml中的配置可以放到servlet中用注解来书写

属性 说明
name 指定servlet的名称
initParams 配置初始化参数
urlPatterns/value 指定Servlet容器处理的url,可配置多个

具体配置如下:

@WebServlet(name = "TextApplication ", 
	urlPatterns = {"/TextApplication","/TextApplication.do"}, 
	initParams = {
		@WebInitParam(name="name", value="name"), 
		@WebInitParam(name="value", value="value")
	}
)
public class TextApplication extends HttpServlet {
	//略
}

你可能感兴趣的:(Java,Web)