在httpd反向代理實踐(一)中,僅僅是使用了httpd來訪問靜態的資源文件,如今咱們搭建真正的動態資源(基於servlet),而後看看反向代理中涉及到的 Content-Location和Location首部,以及cookie的domain和path時的狀況。tomcat
首先是被代理端配置: 服務器
basePath : http://www.example.com:8080/hello cookie
1. 重定向(Location首部)dom
@WebServlet("/dog") public class Dog extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getContextPath(); String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/"; //若是在重定向中不使用徹底路徑,那麼重定向的Location內容就是/hello/cat,此時反向代理就沒法正確的替換了。 //response.sendRedirect(path + "/cat"); //使用徹底路徑:http://www.example.com:8080/hello/cat,在反向代理中將被替換爲 http://www.example1.com/tomcat/cat response.sendRedirect(basePath + "cat"); } }
2.設置cookiespa
@WebServlet("/SetCookie") public class SetCookieServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie nameCookie = new Cookie("name", "zhangsan"); //若是咱們沒有主動設置domain和path的話,那麼即使沒有ProxyPassReverseCookieDomain和ProxyPassReverseCookiePath指令也不會有問題。 nameCookie.setDomain(request.getServerName()); nameCookie.setPath(request.getContextPath()); response.addCookie(nameCookie); try(PrintWriter out = response.getWriter();){ out.print("set name cookie"); } } }
3. 獲取cookie代理
@WebServlet("/GetCookie") public class GetCookieServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try(PrintWriter out = response.getWriter();){ Cookie[] cs = request.getCookies(); if(cs != null){ for(Cookie c : cs){ out.println(c.getName() + " --> " + c.getValue()); } } } } }
代理服務器端的配置:code
按照上面配置搭建被代理環境,若是咱們沒有設置ProxyPassReverse 、ProxyPassReverseCookieDomain和ProxyPassReverseCookiePath的話,那麼將沒法正常重定向和存取cookie。blog