1. 程式人生 > >Context域從web.xml獲取數據學習筆記

Context域從web.xml獲取數據學習筆記

Context域從web.xml獲取數據

web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <context-param>
      <param-name>email</param-name>
      <param-value>[email protected]</param-value>
  </context-param>
    <context-param>
      <param-name>tel</param-name>
      <param-value>13888888888888</param-value>
   </context-param>

java文件

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class webDme extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //取得對象
         ServletContext context = this.getServletContext();
         //從web.xml獲取元素
        String email =  context.getInitParameter("email");
        String tel =  context.getInitParameter("tel");

        if(email != null && tel != null)
        {
        //如果是中文需要加上這個,否則出現亂碼
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("李玟郵箱:"+email+"<br/>");
            response.getWriter().write("李玟電話:"+tel+"<br/>");
        }

    }

}

訪問路徑

http://localhost:8080/day04/webDme

技術分享圖片

Context域從web.xml獲取數據學習筆記