1、a.html去访问b.html有几种方式呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
我是a.html
</div>
<a href="http://localhost:8080/servlet/a1/a2/b.html">方式一: 去b.html</a><br>
<a href="/servlet/a1/a2/b.html"> 方式二: 去b.html</a><br>
<a href="a1/a2/b.html">方式三: 去b.html</a>
</body>
</html>
说明:
(方式二)如果href中第一个是/:浏览器在解析时,会将第一个/解析成http://localhost:8080/ 那么/servlet/a1/a2/b.html会被解析成http://localhost:8080/servlet/a1/a2/b.html
(方式三)如果href中第一个不是/:会根据当前页面的浏览器地址栏地址进行解析,比如当前地址栏为 http://localhost:8080/servlet/a.html 则浏览器会将资源名改为href中的值 http://localhost:8080/servlet/a1/a2/b.html
2、动态资源去访问静态资源
HiServlet如何去访问b.html呢?
@WebServlet(urlPatterns = {"/hi"})
public class HiServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//请求转发
req.getRequestDispatcher("/a1/a2/b.html").forward(req,resp);
// req.getRequestDispatcher("a1/a2/b.html").forward(req,resp);
//
// //重定向
// resp.sendRedirect("http://localhost:8080/servlet/a1/a2/b.html");
// resp.sendRedirect("/servlet/a1/a2/b.html");
// resp.sendRedirect("a1/a2/b.html");
// resp.sendRedirect(getServletContext().getContextPath()+"/a1/a2/b.html");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
说明: 请求转发是被服务器端解析, 重定向是被浏览器端解析
(请求转发方式一) req.getRequestDispatcher("/a1/a2/b.html").forward(req,resp);
带/服务器端会将第一个/解析成应用名 如:/servlet/a1/a2/b.html
(请求转发方式二) req.getRequestDispatcher("a1/a2/b.html").forward(req,resp);
不带/服务器端会根据当前浏览器地址栏进行解析 如:当前地址栏为http://localhost:8080/servlet/hi 会将当前浏览器地址的资源替换成a1/a2/b.html
最后结果为http://localhost:8080/servlet/a1/a2/b.html
(重定向方式一): resp.sendRedirect("http://localhost:8080/servlet/a1/a2/b.html");
告诉浏览器发送请求给"http://localhost:8080/servlet/a1/a2/b.html"
(重定向方式二): resp.sendRedirect("/servlet/a1/a2/b.html");
浏览器在解析时,会将第一个/解析成http://localhost:8080/ 那么/servlet/a1/a2/b.html会被解析成http://localhost:8080/servlet/a1/a2/b.html
(重定向方式三):resp.sendRedirect("a1/a2/b.html");
会根据当前页面的浏览器地址栏地址进行解析,比如当前地址栏为 http://localhost:8080/servlet/hil 则浏览器会将资源名hi改为href中的值 http://localhost:8080/servlet/a1/a2/b.html
总结 :
(浏览器解析)如果第一个是/,浏览器解析会将第一个/解析成http://localhost:8080/,如果不是会根据当前页面的浏览器地址栏地址进行解析,将当前页面的资源名改为请求的资源
(服务器端解析)如果第一个是/,服务器解析会将第一个/解析成应用名,如果不是会根据当前页面的浏览器地址栏地址进行解析,将当前页面的资源名改为请求的资源