Tomcat 中的 URL 映射到 FrontController servlet [英] URL mapping in Tomcat to FrontController servlet

查看:37
本文介绍了Tomcat 中的 URL 映射到 FrontController servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遵循 设计模式基于网络的应用程序 上的模式.从映射根"网址开始,这一切都很好.

I'm trying to follow the pattern at Design Patterns web based applications. It all works fine part from when it comes to maping "root" URLs.

我想把所有请求都通过前端控制器",所以我把

I'd like to put all requests through the "Front Controller" so I've put

<servlet-mapping>
    <servlet-name>ControllerServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

web.xml 中.使用 Netbeans 单步执行会显示请求进入,并且 Action 工作正常,但是接下来是

in the web.xml. Stepping through with Netbeans shows the request coming in, and the Action working OK, but then the line

request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);

也被控制器捕获,它再次进入 Action 并且一切都失败了.

ALSO gets caught by the controller, it goes to the Action again and it all fails.

我可以通过不从 URL 根开始来使它工作,例如

I can make it work by not going from the URL root e.g.

  <servlet-mapping>
        <servlet-name>ControllerServlet</servlet-name>
        <url-pattern>/pages/*</url-pattern>
    </servlet-mapping>

但这不是我想要的.有没有办法让它与根"网址一起工作?

But that isn't what I want. Is there any way to make it work with "root" URLs?

推荐答案

/* URL 模式涵盖了一切,也包括转发的 JSP 文件和静态资源,如 CSS/JS/图像.您不想在前端控制器 servlet 上使用它.

The /* URL pattern covers everything, also the forwarded JSP files and static resources like CSS/JS/images. You don't want to have that on a front controller servlet.

让您的控制器 servlet 使用更具体的 URL 模式,例如 /pages/*.您可以通过将静态资源归类到/resources这样的公共文件夹中并创建映射的Filter来实现去除URL中的/pages"的功能需求在 /* 上并在 doFilter() 方法中执行以下工作:

Keep your controller servlet on a more specific URL pattern like /pages/*. You can achieve the functional requirement of getting rid of "/pages" in the URL by grouping the static resources in a common folder like /resources and creating a Filter which is mapped on /* and does the following job in the doFilter() method:

HttpServletRequest req = (HttpServletRequest) request;
String path = req.getRequestURI().substring(req.getContextPath().length());

if (path.startsWith("/resources/")) {
    // Just let container's default servlet do its job.
    chain.doFilter(request, response);
} else {
    // Delegate to your front controller.
    request.getRequestDispatcher("/pages" + path).forward(request, response);
}

默认情况下,转发的 JSP 资源将不匹配此过滤器,因此它会被容器自己的 JspServlet 正确拾取.

A forwarded JSP resource will by default not match this filter, so it will properly be picked up by the container's own JspServlet.

这篇关于Tomcat 中的 URL 映射到 FrontController servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆