Servlet Mapping using web.xml

泄露秘密 提交于 2019-12-17 03:09:11

问题


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>

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.


回答1:


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>

It allows filters to be mapped on the particular servlet:

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

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.

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

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

See also:

  • How do servlets work? Instantiation, sessions, shared variables and multithreading
  • Difference between each instance of servlet and each thread of servlet in servlets?
  • Our Servlets wiki page


来源:https://stackoverflow.com/questions/8198312/servlet-mapping-using-web-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!