1. 程式人生 > 其它 >JavaWeb獲取web.xml初始引數!getInitParameter

JavaWeb獲取web.xml初始引數!getInitParameter

一、getInitParameter:

解釋:getInitParameter () 方法是在GenericServlet介面中定義的一個方法 ,用來呼叫初始化在 web.xml中存放的參量。

二、程式碼解釋:

①:附:原始碼!原始碼圖!

package com.laugh.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class InitServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext Context = this.getServletContext();
//呼叫初始地址 String url = Context.getInitParameter("url"); resp.getWriter().println(url); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

②:web.xml:附:原始碼!原始碼圖!

<?
xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--我這個頭是新的--> <!--設定web初始化引數--> <context-param> <param-name>url</param-name> <param-value>https://www.cnblogs.com/superyonng</param-value> </context-param> <!--我是提供獲得初始化路徑的方法 InitServlet--> <servlet> <servlet-name>url</servlet-name> <servlet-class>com.laugh.servlet.InitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>url</servlet-name> <url-pattern>/url</url-pattern> </servlet-mapping> </web-app>

③:輸出結果:

學如逆水行舟,不進則退。