web.xml : URL mapping

2019-04-02 10:54发布

问题:

I have these two lines in my web.xml

<url-pattern>/</url-pattern> : Index Servlet
and
<url-pattern>/login</url-pattern> : Login Servlet

but whem I open http://localhost:8084/login/, it goes to Index Servlet and when I open http://localhost:8084/login, it goes to Login Servlet.

Is there any difference in http://localhost:8084/login/ and http://localhost:8084/login?

My web.xml

<servlet>
    <servlet-name>Index</servlet-name>
    <servlet-class>Index</servlet-class>
</servlet>
<servlet>
    <servlet-name>Login</servlet-name>
    <servlet-class>Login</servlet-class>
</servlet>
and

<servlet-mapping>
    <servlet-name>Index</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Login</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

回答1:

The URL pattern of / has a special meaning. It namely indicates the "Default Servlet" URL pattern. So every request which does not match any of the other more specific URL patterns in web.xml will ultimately end up in this servlet. Note that this thus also covers static files like plain vanilla HTML/CSS/JS and image files! Normally, the "Default Servlet" is already provided by the servlet container itself (see e.g. Tomcat's DefaultServlet documentation). Overriding the "Default Servlet" in your own webapp should be done with extreme care and definitely not this way.

You need to give your index servlet a different URL pattern. It should be the same as the one you definied in <welcome-file>.

So in case of

<welcome-file-list>
    <welcome-file>index</welcome-file>
</welcome-file-list>

you need to map the index servlet as follows

<servlet-mapping>
    <servlet-name>Index</servlet-name>
    <url-pattern>/index</url-pattern>
</servlet-mapping>

Using an URL rewrite filter as suggested by other answer is unnecessary for the particular purpose you had in mind.



回答2:

Yes, there is a difference. Either use something like UrlRewriteFilter to remove the trailing slash, or have your web.xml specify both:

<url-pattern>/login</url-pattern>

and

<url-pattern>/login/*</url-pattern>    

As mapping to the login servlet.



回答3:

If you want to make it go to Login Servlet. why not try Spring URL Mapping

@RequestMapping(value="/login", method=RequestMethod.GET)
public String demo(ModelMap map) {

String something = name;

// Do manipulation

return "login"; // Forward to login.jsp
}

Watch this Spring MVC Framework Tutorial