使用 web.xml 的 Servlet 映射 [英] Servlet Mapping using web.xml

查看:28
本文介绍了使用 web.xml 的 Servlet 映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 servlet 映射的 web.xml 结构感到困惑,执行它没有任何问题,但我试图弄清楚为什么我们在部署描述符中有这样的模式.

I have a confusion regarding the structure of the web.xml for the servlet mapping, I don't have any problem by executing it but I am trying to figure it how why we have such a pattern in the deployment descriptor.

<web-app>
    <servlet>
         <servlet-name>Servlet1</servlet-name>
         <servlet-path>foo.Servlet</servlet-path>
    </servlet>
    <servlet-mapping>
         <servlet-name>Servlet1</servlet-name>
         <url-pattern>/enroll</url-pattern>
    </servlet-mapping>
</web-app>

现在,据我所知,每当请求 url-pattern "/enroll" 时,servlet 容器都会将 servlet-name 与 url-pattern 匹配,并尝试找到相应的 servlet-path 并将将控制转发给 foo.Servlet.所以基本上会有两次通过,一次用于查找 servlet-name,另一次用于 servlet-path,我的问题是容器是否设计为按以下方式工作

Now as far as my understanding whenever a request is comes for url-pattern "/enroll", servlet container is going to match the servlet-name with the url-pattern and will try to find the corresponding servlet-path and will forward the control to foo.Servlet. so basically there would be two passes one for finding servlet-name and another for servlet-path, my question is if container is designed to work in the following way

<web-app>
        <servlet>
             <servlet-name>foo.Servlet</servlet-path>
             <url-pattern>/enroll</url-pattern>
        </servlet>
</web-app>

如果我们使用以下方法会有什么缺点.那样会不会更有效率,响应时间也会很快.

what would be the drawback if we use the following approach. Wouldn't that be more efficient and the response time would be fast.

推荐答案

它允许 servlet 有多个 servlet 映射:

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

它允许将过滤器映射到特定的 servlet:

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

你的提议不会支持他们中的任何一个.请注意,web.xml 仅在应用程序启动期间读取和解析一次,而不是像您想象的那样在每个 HTTP 请求上读取和解析.

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

从 Servlet 3.0 开始,就有了 @WebServlet 注释,可最小化此样板:

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

另见:

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