zoukankan      html  css  js  c++  java
  • 使用监听器解决路径问题,例如在jsp页面引入js,css的web应用路径

    使用监听器解决路径问题,例如在jsp页面引入js,css的web应用路径

    经常地,我们要在jsp等页面引入像js,css这样的文件,但是在服务器来访问的时候,这时间就有关到相对路径与绝对路径了。像网页这种,我们不可能去写死一个绝对路径,就需要来写相对路径。

    一、要想在jsp页面中引入 js,css等文件,web应用的路径可以使用${pageContext.request.ContextPath}

    例如:

    <script src="${pageContext.request.contextPath}/jquery/jquery-2.1.1.min.js"></script>

    二、使用监听器解决路径问题

    1、先写一个类来实现ServletContextListener,覆写里面的接口

    例如先写一个ServletStartUpListener.class

    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    /**
     * 资源访问路径监听
     */
    public class ServletStartUpListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            //将web用户名称保存到application中去
            ServletContext application = servletContextEvent.getServletContext();
            String contextPath = application.getContextPath();
            application.setAttribute("APP_PATH",contextPath);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
    
        }
    }

     2、在web.xml文件中配置监听器,让应用在启动的时候监听到,并执行初始化方法,将web用户名称保存到application中去

      <!--使用监听器配置web路径-->
      <listener>
        <listener-class>com.lzc.rbac.web.ServletStartUpListener</listener-class>
      </listener>

     3、再在我们的jsp页面使用监听器解决路径问题

    例如:

    <script src="${APP_PATH}/jquery/jquery-2.1.1.min.js"></script>

     这里的${APP_PATH}就是获取在上面实现ServletContextListener类中的contextInitialized()方法里面设置的属性值application.setAttribute("APP_PATH",contextPath);

  • 相关阅读:
    打开安装 好的Microsoft Dynamics CRM 4.0 报错误为 Caller does not have enough privilege to set CallerOriginToken to the specified value 的解决办法
    基于 Windows Server 2008 的计算机对 Microsoft Dynamics CRM 4.0 的支持
    Microsoft Dynamics CRM 4.0 如何添加自定义按钮
    Microsoft Dynamics CRM 4.0 Plugin 取值,赋值,查询
    C# 中的 enum(枚举) 类型使用例子
    vue事件的绑定
    表单验证2
    node中模块
    node模块的引入
    node中的读文件
  • 原文地址:https://www.cnblogs.com/limn/p/9502955.html
Copyright © 2011-2022 走看看