1. 程式人生 > >Servlet:獲取初始化引數

Servlet:獲取初始化引數

    今天我們來看一下如何獲取Servlet的初始化引數。首先在web.xml檔案中進行引數的初始化,利用標籤<init-param><param-name>,<param-value>:

<?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>param</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file
>
<welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>param</servlet-name> <servlet-class>servlet.param</servlet-class> <init-param> <param-name
>
username</param-name> <param-value>wu</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>param</servlet-name> <url-pattern>/servlet/param</url-pattern> </servlet-mapping> </web-app>

在servlet中獲取該初始化引數:

package servlet;

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;

public class param extends HttpServlet {
    private String username;

public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
public param() {
    // TODO Auto-generated constructor stub
}
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setHeader("content-type", "text/html;charset=utf-8");  
    response.setCharacterEncoding("utf-8");
    request.setCharacterEncoding("utf-8");
    PrintWriter out=response.getWriter();
        out.println("訪問成功!");
        out.println(this.getUsername());
    }
@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
@Override
public void init() throws ServletException {
    this.setUsername(this.getInitParameter("username"));//獲取初始化引數
}
}

    這樣就可以獲取到初始化引數了。