JSP中<base href="<%=basePath%>">作用

本文详细解读了如何通过Java代码获取当前项目路径,并在HTML页面中设置基础路径,以便统一管理资源链接。通过示例代码演示了获取上下文路径和服务器基本信息的方法,以及如何在HTML中应用这些路径来简化资源引用。

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

代码   收藏代码
  1. <%  
  2. String path = request.getContextPath();  
  3. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  4. %>  

 

这段代码的意思是获取当前项目的路径,如:http://localhost:8080/项目名称。

 

在<head></head>中通常有如下代码:

 

Java代码   收藏代码
  1. <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、付费专栏及课程。

余额充值