1 分别单独给某个Servlet 以及 ServletContext 设置配置信息并获取,截图展示结果
Servlet
public class zyServlet extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("初始化");
}
@Override
public ServletConfig getServletConfig() {
ServletConfig servletConfig = super.getServletConfig();
System.out.println("zyServlet的配置对象:" + servletConfig);
return servletConfig;
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("响应客户端请求, hhhh" );
ServletConfig servletConfig = this.getServletConfig();
System.out.println("zyServlet的相关信息" + servletConfig);
}
@Override
public void destroy() {
System.out.println("zyServlet的销毁方法");
}
}
web.xml文件代码
<servlet>
<servlet-name>zyServlet</servlet-name>
<servlet-class>com.qiku.web.zyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>zyServlet</servlet-name>
<url-pattern>/zyServlet</url-pattern>
</servlet-mapping>
运行结果:
ServletContext
@WebServlet(name = "zyServletContext" , urlPatterns = "/zycontext")
public class zyServletContext extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext zycontext = getServletConfig().getServletContext();
ServletContext servletContext = getServletConfig().getServletContext();
System.out.println(servletContext);
Enumeration<String> initParameterNames = zycontext.getInitParameterNames();
while(initParameterNames.hasMoreElements()){
String s = initParameterNames.nextElement();
System.out.println(s + "对应的值" + zycontext.getInitParameter(s));
}
String contextPath = zycontext.getContextPath();
System.out.println("相对路径:" + contextPath);
String realPath = zycontext.getRealPath("/");
System.out.println("绝对路径:" +realPath);
zycontext.setAttribute("param2","values2");
Object param2 = zycontext.getAttribute("param2");
System.out.println("根据属性名获得属性值:" + param2);
zycontext.removeAttribute("param2");
param2 = zycontext.getAttribute("param2");
System.out.println("根据属性名删除属性值:" + param2);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("do get");
doPost(req,resp);
}
}
xml文件 :
<context-param>
<param-name>username</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>123456789</param-value>
</context-param>
结果: