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

查看:475
本文介绍了使用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天全站免登陆