通过Servlet获取初始化参数
获取初始化参数
在web.xml中配置Servlet时,可以配置一些初始化参数。而在Servlet中可以通过ServletConfig接口提供的方法来获取这些参数。(其实还可以通过ServletContext来获得参数,只不过ServletConfig获得的参数是容器启动的时候就初始化的,而ServletConfig是Servlet类调用init()函数的时候才初始化的)。
因为我们的初始哈参数是配置在servlet里面的,所以我们这里以username为例,我们假设要在我们的moonlit servlet中添加一个初始化属性username,我们可以在web.xml中对应的servlet中添加init-param属性,如下:
<init-param> <param-name>username</param-name> <param-value>moonlit</param-value> </init-param>
完整的web.xml文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>WebProject</display-name> <servlet> <servlet-name>moonlit</servlet-name> <servlet-class>com.moonlit.MoonlitServlet</servlet-class> <init-param> <param-name>username</param-name> <param-value>moonlit</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>moonlit</servlet-name> <url-pattern>/getinit.do</url-pattern> </servlet-mapping> </web-app>
然后我们就可以在moonlit servlet对应的类中通过getParameter()方法获得username这个初始化参数对应的值,如下:
String username = this.getInitParameter("username");
完成的MoonlitServlet类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.moonlit; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class MoonlitServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); String username = this.getInitParameter("username"); out.println("<html>" + "<head><title>moonlit servlet</title></head>" + "<body>" + username + "</body>" + "</html>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
然后我们可以通过对应的url-pattern访问到这个servlet对应的网页。
效果如下: