本文主要是介绍ServletConfig对象.,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
是什么
ServletConfig是javax.servlet.包下的一个接口,ServletConfig它是Servlet的一个配置对象;
ServletConfig是由tomcat容器创建,通过init方法传入给Servlet;
-
ServletConfig对象如何获取?
在GenericServlet里面定义了:
public ServletConfig getServletConfig() {return this.config;
}
-
常用方法
getInitParameter(String parameterName); //根据参数名称获取指定的参数值
getInitParameterNames(); //获取所有的参数名称
在web.xml文件中配置一下:
<servlet><servlet-name>ServletConfigServlet</servlet-name><servlet-class>com.by.servlet.ServletConfigServlet</servlet-class><init-param><param-name>username</param-name><param-value>Tom</param-value></init-param><init-param><param-name>password</param-name><param-value>123</param-value></init-param></servlet><servlet-mapping><servlet-name>ServletConfigServlet</servlet-name><url-pattern>/servletConfigServlet</url-pattern></servlet-mapping>
在ServletConfigServlet这个类中调用一下:
/** Copyright (c) 2020, 2023, All rights reserved.**/
package com.by.servlet;import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** <p>Project: JavaWeb-Servlet - ServletConfigServlet</p>* <p>Powered by scl On 2023-12-26 15:52:05</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
public class ServletConfigServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletConfig servletConfig = getServletConfig();String username = servletConfig.getInitParameter("username");String password = servletConfig.getInitParameter("password");System.out.println(username+password);}
}
结果展示:
这篇关于ServletConfig对象.的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!