问题:在Servlet中进行转发或者重定向后,跳转至目标页面(例index.jsp),但是页面的CSS和JavaScript样式失效,页面混乱
原因是Servlet跳转时,目标页面(例index.jsp)中的CSS、JS的路径是这个Servlet的相对路径,而不再是目标页面(例index.jsp)的相对路径。
跳转至目标页面后(观察地址末端)
浏览器中地址栏:http://localhost:10080/Demo_Platform/webapp/login
样式失效,页面内容混乱
而不是目标页面:http://localhost:10080/Demo_Platform/JSP/index.jsp
单独打开目标页面,页面的CSS和JS样式是生效了的
解决方案:
在HTML或JSP页面中的<head>标签中添加以下内容
```
<head>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<base href="<%=basePath%>">
<link href="<%=basePath%>/css/public.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<%=basePath%>/js/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/js/global.js"></script>
</head>
```
最近在复习JavaWeb知识,把点点滴滴问题记录下来,做到知其然知其所以然,加油!