Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have been readin Head First JSP and Servlet, I see that the web.xml has

  <!-- To name the servlet -->
  <servlet>                                    
    <servlet-name>ServletName</servlet-name>
    <servlet-class>packy.FirstServlet</servlet-class>
  </servlet>

  <!-- For URL's to map to the correct servlet -->
  <servlet-mapping>
    <servlet-name>ServletName</servlet-name>
    <url-pattern>/ServletURL</url-pattern>
  </servlet-mapping>

Why hide the original servlet's location ? I can simply see that it is for security reason and some more such kinda advantages, but why have a name for each servlet ? Why can't the web.xml be simple like

  <servlet>                                    
    <url-pattern>ServletURL</url-pattern>
    <servlet-class>packy.FirstServlet</servlet-class>
  </servlet>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
94 views
Welcome To Ask or Share your Answers For Others

1 Answer

It allows you to have multiple servlet mappings on a single servlet instance (even spread over multiple web.xml/web-fragment.xml files) without the unnecessary need to create a separate instance per mapping:

<servlet>
    <servlet-name>someServlet</servlet-name>
    <servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>someServlet</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>someServlet</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>someServlet</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

(note: yes, you can have multiple URL patterns per mapping, but that wouldn't cover them being split over multiple web.xml/web-fragment.xml files)

It allows you to map filters on the particular servlet without worrying about what URL patterns the servlet is/would be using:

<filter-mapping>
    <filter-name>someFilter</filter-name>
    <servlet-name>someServlet</servlet-name>
</filter-mapping>

Your proposal would support neither of them.

Note that since Servlet 3.0, which is out for almost 4 years already (December 2009; please make sure that you learn the matters by up to date resources ... anything older than 1~3 years should be carefully reviewed), you can easily use the @WebServlet annotation to minimze web.xml boilerplate:

@WebServlet("/servletURL")
public class SomeServlet extends HttpServlet {}

Just solely this annotation already maps it on an URL pattern of /servletURL without any web.xml entry.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...