通过Java Filter后使用RequestDispatcher进行转发



首先让我描述一下我想做的事情,我猜这很简单。我有一个包含用户的网站,希望仅限登录用户访问view_profile.jsp页面。我有一个过滤器映射到:

<url-pattern>/auth/*</url-pattern>

看起来像这个

        try {
        HttpSession session = ((HttpServletRequest)request).getSession();
        UserBean user = (UserBean)session.getAttribute("currentUser");
        if (user != null && user.isValid()){
            System.out.println("Filter: context -> " + ((HttpServletRequest)request).getContextPath()); //returns ""
            chain.doFilter(request, response);
        }
        else{
            ((HttpServletResponse)response).sendRedirect("/login.jsp"); //works fine
        }

当用户在index.jsp页面上点击一个链接时,这个过滤器就会运行:

<a href="./auth/view_profile?profile=${sessionScope.currentUser.username}">
//yeah, he will 'view' himself - it's just an example

假设将用户带到映射到ViewProfileServlet的servlet,该servlet映射到:

<url-pattern>/auth/view_profile</url-pattern>

看起来是这样的:

    try {
        String username = (String) request.getParameter("profile");
        // here is getting info from database and setting request attributes
        // works fine
                //response.sendRedirect("/view_profile.jsp");
                System.out.println("ViewProfileServlet: In context -> " + getServletContext().getContextPath()); // returns ""
                dis = getServletContext().getRequestDispatcher("/view_profile.jsp");
                // i've tried request.getRequestDispatcher. no difference
                System.out.println("ViewProfileServlet: forward to '/view_profile.jsp'");
                dis.forward(request, response);
            }

这反过来应该将用户带到/view_profile.jsp(在根上下文中,而不是在/auth中)并工作,但它没有。发生的情况是ViewProfileServlet运行,view_profile.jsp显示,尽管上下文似乎仍然是/auth,因为view_proffile.jsp上的所有链接都指向localhost:8080/auth/some-page.jsp。此外,css文件没有被加载,甚至没有被请求(至少根据firebug),页面源显示404 Glassfish错误,css应该在那里。

我将非常感谢任何帮助,这是我第一次在jsp中做一些事情,我在这里完全迷失了方向。

转发完全发生在服务器端。浏览器并不知道这一点。当它向/auth/view_profile发送请求,并从该响应中接收HTML时,他不在乎HTML是由servlet、JSP还是两者生成的。它读取HTML并认为它来自路径/auth/view_profile。因此,HTML中的所有相对路径都是相对于/auth/view_profile的。

使用绝对路径引用图像、JS和CSS路径(大多数时候甚至是其他操作)要容易得多。只需确保使用<c:url>标记来生成URL,以便预先准备好web应用程序的上下文路径:

<script src="<c:url value='/js/myScript.js'/>" type="text/javascript"/>
                           ^-- the slash here makes the path absolute. 

相关内容

  • 没有找到相关文章

最新更新