JSP中<base href="<%=basePath%>">对相对路径的影响

本文介绍了在JSP页面中如何使用动态生成的基础路径来确保链接的正确性。通过设置&lt;base href&gt;标签,可以简化页面内的相对链接路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果在JSP中存在

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

和<base href="<%=basePath%>">
,那么在写文件的相对路径的时候,需要把该文件在当前项目下的具体路径写出来。比如如果jsptest.jsp想访问files/andy.js,则需要写成<a href="json/files/andy.js">Andy</a>,而不是<a href="files/andy.js">Andy</a>。这是因为,<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>的作用是获取当前项目的路径,如:http://localhost:8080/项目名称。

            <base href="<%=basePath%>">是设置基础路径的,basePath为变量,简单的静态网页的话你设置比如:<base href="http://www.baidu.com">,那你下面的href属性就会以你上面设的为基准,如:<a href="http://www.baidu.com/xxx.htm"></a>你现在就只需要写<a href="xxx.htm"></a>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'main_left.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <style> body { font-size: 35px; /* 设置字体大小 */ text-align: center; /* 设置文本居中对齐 */ background-color: black; color: white; font-family: Arial, sans-serif; } a { color: white; text-decoration: none; margin: 10px; padding: 10px; } </style> </style> </head> <body> <br><br> <a href="inputStuInfo.jsp" target="main_right">录入学生信息</a><br><br> <a href="student/queryAllStuServlet?osid=query&page=1" target="main_right">查看学生信息</a><br><br> <a href="student/queryAllStuServlet?osid=modify&page=1" target="main_right">修改学生信息</a><br><br> <a href="student/queryAllStuServlet?osid=delete&page=1" target="main_right">删除学生信息</a><br><br> <a href="user/exitServlet" target="_top">退出</a><br> </body> </html> 解释代码
05-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值