javaweb 项目中 求 basePath中的方法

首先 我们建一个basePathFilter

public class BasePathFilter implements Filter{



public void destroy() {
// TODO Auto-generated method stub

}


public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
String prjPath = request.getScheme() + "://" + request.getServerName() + (request.getServerPort() == 80 ? "" : ":" + request.getServerPort()) + request.getContextPath();
request.setAttribute("basePath", prjPath);
arg2.doFilter(arg0, arg1);

}


public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}


}

2 然后再web.xml添加过滤器  

<filter>
    <filter-name>basePathFilter</filter-name>
    <filter-class>com.rf.sys.filter.BasePathFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>basePathFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


3然后我们可以页面活其他地方引用了



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/inc/head.jsp"%>
<html>
<head>
<title>运输工具单一窗口(客线)</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css"  href="${basePath}/css/themes/bootstrap/easyui.css"  />
<link rel="stylesheet" type="text/css" href="${basePath}/css/login.css">
<script src="${basePath}/js/jquery.min.js" type="text/javascript"></script>
<script src="${basePath}/js/jquery.easyui.min.js" type="text/javascript"></script>
<script src="${basePath}/js/locale/easyui-lang-zh_CN.js" type="text/javascript"></script>
<script type="text/javascript">




也可以在页面中写


<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

这个语句是用来拼装当前网页的相对路径的。

<base href="...">是用来表明当前页面的相对路径所使用的根路径的。
比如,页面内部有一个连接,完整的路径应该是 http://localhost:80/myblog/authen/login.do
其中http://server/是服务器的基本路径,myblog是当前应用程序的名字,那么,我的根路径应该是那么http://localhost:80/myblog/。

有了这个 <base ... >以后,我的页面内容的连接,我不想写全路径,我只要写 authen/login.do就可以了。服务器会自动把 <base ...>指定的路径和页面内的相对路径拼装起来,组成完整路径。
如果没有这个 <base...>,那么我页面的连链接就必须写全路径,否则服务器会找不到。

request.getSchema()可以返回当前页面使用的协议,就是上面例子中的“http”
request.getServerName()可以返回当前页面所在的服务器的名字,就是上面例子中的“localhost"
request.getServerPort()可以返回当前页面所在的服务器使用的端口,就是80,
request.getContextPath()可以返回当前页面所在的应用的名字,就是上面例子中的myblog
这四个拼装起来,就是当前应用的跟路径了


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值