Web应用中的路径问题
问题:
由于使用转发跳转页面时,地址栏不变。此时使用相对路径(…/) 不可靠,可能出现404现象。
所以使用绝对路径解决此问题。
什么是绝对路径:
以"/" 开头的路径,称之为绝对路径。
"/"代表什么意义:
1. "/"由服务器解析,代表当前项目路径:http://localhost:8080/day06_servlet
* 以下两种情况由服务器解析
* web.xml中url
* 转发
* 如:request.getRequestDispatcher("/pages/login_success.html").forward(request, response);
注意:pages 前需要带"/"
2. "/"由浏览器解析,代表当前服务器路径:http://localhost:8080
* 以下两种情况由浏览器解析
* 书写在.html中路径,如:img|script:src,link|a:href,form:action,由浏览器解析
* 重定向
* 如:response.sendRedirect(request.getContextPath()+"/pages/login.html");
因为浏览器默认的路径为:http://localhost:8080,不是项目的根路径,所以需要把项目的根路径加上。
动态获取项目名称
request.getContextPath(); -----------> 一般用于重定向的时候,因为转发默认的有项目根路径
示例:
response.sendRedirect(request.getContextPath()+"/pages/login.html");
在HTML页面简化路径
简化路径就是把共同的路径部分提取出来
语法:
<base href="部分相同路径名"/>
如:
url路径中肯定包含项目名,我们把它提取出来。
意思是:该页面只要包含路径问题,所有的路径都默认在前面加上 /day06_servlet/
<base href="/day06_servlet/">
总结:
相对路径不靠谱,应避免使用。
原因:
在请求转发模式下,超链接地址如果使用相对路径,以自身为基准,会导致浏览器URL地址解析错误, 所以应避免使用相对路径。
代码示例
前端
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<base href="/day06_servlet/"> <!--默认所有的路径都加上/day06_servlet/--> 关键点
</head>
<body>
<div align="center">
<h2>登录页面</h2>
<form action="LoginServlet" method="get">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" id="username" name="username" ></td>
</tr>
<tr>
<td>密码:</td>
<td><input id="pwd" type="password" name="pwd" ></td>
</tr>
<tr align="center">
<td colspan="2">
<input type="reset">
<input id="btnSub" type="submit" value="登录">
</td>
</tr>
</table>
</form>
</div>
<a href="index.html">回首页</a>
</body>
</html>
后端
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 取login.html(username&pwd)值
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
System.out.println("username:"+username);
//2. 判断,登录成功|失败
if("zhangsan".equals(username) && "123456".equals(pwd)) {
//登录成功,转发login_success.html
request.getRequestDispatcher("/pages/login_success.html").forward(request, response);
}else {
//失败:重定向login.html(login.html)
//获取项目的虚拟路径:(/day06_servlet),request.getContextPath()
// response.sendRedirect("/day06_servlet/pages/login.html");
response.sendRedirect(request.getContextPath()+"/pages/login.html");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}