当前位置: 首页 > article >正文

servlet中的ServletContext

设置、获取ServletContext配置信息

与ServletConfig不同的是,所有Servlet共享一份ServletContext

  1. 在web.xml中设置配置信息

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
             version="6.0">
        <context-param>
            <param-name>key1</param-name>
            <param-value>a</param-value>
        </context-param>
        <context-param>
            <param-name>key2</param-name>
            <param-value>b</param-value>
        </context-param>
    </web-app>
    
  2. 在service方法中读取

    public class ServletTest extends HttpServlet {
    	public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		ServletContext servletContext = this.getServletContext();
    		
    		// 获取指定的配置信息
    		String value = servletContext.getInitParameter("key2");
    		System.out.println(value);
    		
    		// 批量获取配置信息
    		Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
    		while(initParameterNames.hasMoreElements()) {
    			String key = initParameterNames.nextElement();
    			System.out.println(key + "=" + servletContext.getInitParameter(key));
    		}
    	}
    } 
    

通过ServletContext获取项目实际部署的根路径:getRealPath()

ServletContext servletContext = this.getServletContext();
// 获取项目实际部署的根路径(绝对路径)
String rootPath = servletContext.getRealPath(""); // D:\workspace\javawebproject\out\artifacts\demo1_war_exploded\
// 获取项目实际部署的根目录下的static路径(绝对路径)
String staticPath = servletContext.getRealPath("static"); // D:\workspace\javawebproject\out\artifacts\demo1_war_exploded\static

通过ServletContext获取项目的访问路径:getContextPath()

ServletContext servletContext = this.getServletContext();
// 获取项目的访问路径
String accessPath = servletContext.getContextPath(); // /demo1

http://www.kler.cn/a/547496.html

相关文章:

  • 最大痛点理论
  • -bash:/usr/bin/rm: Argument list too long 解决办法
  • 【情感识别】SECap: Speech Emotion Captioning with Large Language Model 论文阅读
  • Lineageos 22.1(Android 15)更换开机动画
  • Github 2025-02-13Go开源项目日报 Top10
  • 性格测评小程序04题库管理
  • 数据结构与算法之排序算法-归并排序
  • 基于 SpringBoot 的 4S店车辆管理系统 系统的设计与实现
  • 数据科学之数据管理|统计学
  • Map 和 Set
  • React组件的生命周期
  • Java面试常见知识点总结
  • 备战蓝桥杯:贪心算法之货仓选址
  • Window下Redis的安装和部署详细图文教程(Redis的安装和可视化工具的使用)
  • 【kafka系列】消费者重平衡
  • CAS单点登录(第7版)25.通知
  • 如果 main 里面引入 axios ,然后引入 router ,而 router 里面也引入 axios,会不会重复
  • 2月第九讲“探秘Transformer系列”
  • 位图(C语言版)
  • 前后端的身份认证