javaWeb项目中获取项目路径的一些方法解释

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq32933432/article/details/81004543

API

假设请求的页面是index.jsp,项目是WebDemo,则在index.jsp中获取有关request对象的各种路径信息如下

获取方式 结果 解释
request.getContextPath() /WebDemo 项目名称
request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+”/” http://localhost:8683/WebDemo/
request.getRemoteAddr() 127.0.0.1 请求地址
request.getServletPath() /index.jsp 页面名称
request.getRealPath(“/”)或者request.getSession().getServletContext().getRealPath()推荐使用后者,前者已经过期了 D:\apache-tomcat-6.0.13\webapps\WebDemo\ 获取项目的绝对路径
request.getRemoteUser(); null 这个没太弄懂
request.getRequestURI() /WebDemo/index.jsp 获取页面的相对路径

一般用法

很多项目中会采用以下用法
页面 A.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@include file="/context/mytags.jsp" %><!--此处引入公共的文件-->
<!DOCTYPE html>
<html>
<!--请求URL一般会写成以下形式,这个webRoot实际上是在上面引入的公共JSP:mytags.jsp里面定义的-->
${webRoot}/xxx/xxxx
<!--省略其他代码-->
</html>

mytags.jsp

<%@ taglib prefix="t" uri="/easyui-tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%>
<% 
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<c:set var="webRoot" value="<%=basePath%>" /><!--此处引入webRoot共使用-->

猜你喜欢

转载自blog.csdn.net/qq32933432/article/details/81004543
今日推荐