JavaScript与Java后端获取当前路径的方法示例

作者:岩茶时间:2026-10-27 21:04:44浏览:331

本文介绍了在Web开发中获取当前页面路径的多种实现方式。前端部分展示了JavaScript中document.URL、location.href等属性的区别及通过split截取页面名称的方法。后端部分列举了Java Servlet API中request对象获取URI、URL、查询字符串及Servlet路径的关键方法,并给出了组合生成完整网络地址的示例代码。

JavaScript获取当前路径与主机信息

<script type="text/javascript"> // 获取当前文档的URL thisURL = document.URL; // 获取当前窗口的href属性 thisHREF = document.location.href; // 获取self对象的location.href thisSLoc = self.location.href; // 获取document的location对象 thisDLoc = document.location; // 拼接输出字符串 strwrite = " thisURL: [" + thisURL + "]<br />" strwrite += " thisHREF: [" + thisHREF + "]<br />" strwrite += " thisSLoc: [" + thisSLoc + "]<br />" strwrite += " thisDLoc: [" + thisDLoc + "]<br />" // 将结果写入文档 document.write( strwrite );

// 获取顶层窗口的location.href thisTLoc = top.location.href; // 获取父文档的location thisPLoc = parent.document.location; // 获取顶层窗口的hostname thisTHost = top.location.hostname; // 获取当前location的hostname thisHost = location.hostname; // 拼接输出字符串 strwrite = " thisTLoc: [" + thisTLoc + "]<br />" strwrite += " thisPLoc: [" + thisPLoc + "]<br />" strwrite += " thisTHost: [" + thisTHost + "]<br />" strwrite += " thisHost: [" + thisHost + "]<br />" // 将结果写入文档 document.write( strwrite );

// 通过split分割URL获取页面名称 // 处理thisHREF var tmpHPage = thisHREF.split( "/" ); var thisHPage = tmpHPage[ tmpHPage.length-1 ]; // 处理thisURL var tmpUPage = thisURL.split( "/" ); var thisUPage = tmpUPage[ tmpUPage.length-1 ]; // 拼接输出字符串 var strwrite = " thisHPage: [" + thisHPage + "]<br />" strwrite += " thisUPage: [" + thisUPage + "]<br />" // 将结果写入文档 document.write( strwrite ); // Java后端获取URI并弹出提示 var url="<%=request.getRequestURI()%>"; alert(url) </script>

Java Servlet Request对象路径获取方法

// Java Servlet API中获取路径相关的方法列表 request.getRequestURI(); request.getRequestURL(); request.getQueryString();

// 获取Servlet路径 request.getServletPath()

// 组合生成完整的网络地址 // 格式为 scheme://serverName:serverPort + requestURI var fullUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getRequestURI()

作者最新文章