ServletContext的获取初始化参数

ServletContext获取初始化参数

获取的是web.xml中的参数。

1、 创建class

 

 1 package com.wang.servlet;
 2 
 3 import javax.servlet.ServletContext;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.io.IOException;
 9 
10 public class ServletDeno03 extends HttpServlet {
11     @Override
12     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
13         ServletContext context = this.getServletContext();
14         String url = context.getInitParameter("url");
15         resp.getWriter().print(url);
16 
17     }
18 
19     @Override
20     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
21         doGet(req, resp);
22     }
23 }
View Code

2、 web的初始化参数

3、 注册和映射

 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
 5                       http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 6          version="4.0"
 7          metadata-complete="true">
 8     <!--web的初始化参数-->
 9     <context-param>
10         <param-name>url</param-name>
11         <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
12     </context-param>
13     
14     <!--注册和映射-->
15     <servlet>
16         <servlet-name>gp</servlet-name>
17         <servlet-class>com.wang.servlet.ServletDeno03</servlet-class>
18     </servlet>
19     <servlet-mapping>
20         <servlet-name>gp</servlet-name>
21         <url-pattern>/gp</url-pattern>
22     </servlet-mapping>
23 
24 </web-app>
View Code

4、 改Tomcat的名字,运行

  

通过上述,获取了web应用的初始化参数。

posted @ 2020-03-24 19:15  WZ_BeiHang  阅读(643)  评论(0编辑  收藏  举报