servlet获取初始化配置信息

原创 Laughing  2017-11-10 21:51  阅读 385 次 评论 0 条

继承HttpServlet

  1. package me.lisen.JavaEEStudy;  
  2.   
  3. import com.sun.xml.internal.ws.api.WSService;  
  4.   
  5. import javax.servlet.ServletConfig;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.annotation.WebServlet;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import java.io.IOException;  
  12. import java.io.PrintWriter;  
  13.   
  14. @WebServlet(name = "HelloServlet")  
  15. public class HelloServlet extends HttpServlet {  
  16.   
  17.     public String initParam;  
  18.     public void init(ServletConfig config) throws ServletException{  
  19.         initParam = config.getInitParameter("website");  
  20.     }  
  21.   
  22.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  23.   
  24.     }  
  25.   
  26.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  27.        PrintWriter printWriter= response.getWriter();  
  28.        response.setCharacterEncoding("UTF-8");  
  29.        printWriter.println(initParam);  
  30.        printWriter.close();  
  31.     }  
  32. }  

配置web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"  
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"  
  5.          version="3.1">  
  6.     <servlet>  
  7.         <servlet-name>hello</servlet-name>  
  8.         <servlet-class>me.lisen.JavaEEStudy.HelloServlet</servlet-class>  
  9.         <init-param>  
  10.             <param-name>website</param-name>  
  11.             <param-value>www.lisen.me</param-value>  
  12.         </init-param>  
  13.     </servlet>  
  14.     <servlet-mapping>  
  15.         <servlet-name>hello</servlet-name>  
  16.         <url-pattern>/HelloServlet</url-pattern>  
  17.     </servlet-mapping>  
  18. </web-app>  
HttpServlet 还有一个不带参数的init(),当两个方法同时实现时,将调用带参数的方法。
本文地址:https://www.lisen.me/servlet-gets-initialization-configuration-information.html
版权声明:本文为原创文章,版权归 木子网 所有,欢迎分享本文,转载请保留出处!

发表评论


表情