通过Java筛选器后使用RequestDispatcher进行转发

通过Java筛选器后使用RequestDispatcher进行转发,java,jsp,servlets,servlet-filters,requestdispatcher,Java,Jsp,Servlets,Servlet Filters,Requestdispatcher,首先,让我描述一下我想做的事情,我猜这很简单。 我有一个有用户的网站,我想限制只有登录用户才能访问view_profile.jsp页面。我已将筛选器映射到: <url-pattern>/auth/*</url-pattern> <url-pattern>/auth/view_profile</url-pattern> 当用户在index.jsp页面上单击以下链接时,将运行此筛选器: <a href="./auth/view_profile

首先,让我描述一下我想做的事情,我猜这很简单。 我有一个有用户的网站,我想限制只有登录用户才能访问view_profile.jsp页面。我已将筛选器映射到:

<url-pattern>/auth/*</url-pattern>
<url-pattern>/auth/view_profile</url-pattern>
当用户在index.jsp页面上单击以下链接时,将运行此筛选器:

<a href="./auth/view_profile?profile=${sessionScope.currentUser.username}">
//yeah, he will 'view' himself - it's just an example
反过来,它应该将用户带到/view_profile.jsp(在根上下文中,而不是在/auth中)并工作,但它不工作。所发生的事情是ViewProfileServlet运行,view_profile.jsp显示,尽管看起来上下文仍然是/auth,因为view_profile.jsp上的所有链接都指向localhost:8080/auth/some-page.jsp。此外,css文件并没有被加载,甚至并没有被请求(至少根据firebug),页面源代码显示了404 Glassfish错误,而css应该是这样的


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

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

使用绝对路径来引用图像、JS和CSS路径(大多数情况下甚至是其他操作)要容易得多。只需确保使用
标记生成URL,以便在web应用程序的上下文路径前面加上前缀:

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

^--这里的斜线使路径成为绝对路径。

谢谢你的回答。我已将css的路径更改为1,但发生的情况是,在一秒钟内,它请求“localhost:8080/auth/css/styles.css”,该请求(再次)通过过滤器,然后css请求完全消失。结果是一样的。路径必须是绝对的:从
/
开始。谢谢:)Css有效。但是我该如何处理页面上的链接呢?是否有任何方法使它们不指向/auth/context?我已经尝试过了,但它仍然指向/auth/logout.jsp
    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);
            }
<script src="<c:url value='/js/myScript.js'/>" type="text/javascript"/>
                           ^-- the slash here makes the path absolute.