取得上下文路径的方式(getContextPath)

jsp可以直接取得取得上下文路径,但是js不能,需要在jsp里设置属性再根据属性获取或者通过window.loaction的方式做处理后取得。

1.通过监听器,获取

1.1web.xml文件配置监听器(java类名全路径)

<listener>
<listener-class>com.stuwork.crowdfunding.listener.StartSystemListener</listener-class>
</listener>

 1.2 java文件方法

package com.stuwork.crowdfunding.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class StartSystemListener implements ServletContextListener {

@Override
public void contextDestroyed(ServletContextEvent sce) {
}

//服务器启动,创建application对象时候执行的方法
@Override
public void contextInitialized(ServletContextEvent sce) {
//将上下文路径放到application域中(request.getContextPath())
ServletContext application = sce.getServletContext();
String contextPath = application.getContextPath();
application.setAttribute("CWF_PATH", contextPath);

}

}

 1.2jsp页面取得。

<script src="${CWF_PATH}/static/script/docs.min.js"></script>

 2 jsp页面直接脚本获取(request.getContextPath()方式)

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String path = request.getContextPath()+ "/index.htm";
response.sendRedirect(path);
%>

<!-- 取得上边的path值 -->

<a href="<%=path %>/test.jsp">

</body>

</html>

 3 通过jstl取得上下文并设置属性(需要引入c标签)

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx_jsp" value="${pageContext.request.contextPath}"/>
<input type="hidden" id="ctx_js" value="${ctx }">

 jsp和js文件取得方式

jsp文件取得

可以过${ctx_jsp}和$("#ctx_js")取得

js文件取得

只能通过$("#ctx_js")取得

 

 

原文地址:https://www.cnblogs.com/konglxblog/p/14068970.html