How to use @WebServlet to accept arguments (in a R

2019-05-30 04:39发布

问题:

suppose that I want to accept the following urls:

http://myserver/myapplication/posts
http://myserver/myapplication/posts/<id>
http://myserver/myapplication/posts/<id>/delete

how can I use the servlet decorator @WebServlet to do so? I'm investigating value and urlPatterns but I don't get how to do so. For example,

@WebServlet(urlPatterns={"/posts", "/posts/*"})
[..]
String param = request.getPathInfo();

gives me some result, but how to use it? Also, request.getPathInfo() seems to return the value of the wildcard, but what if I want more parameters like in http://http://myserver/myapplication/posts/<id>/delete/<force>?

回答1:

In servlet specification, you have no notion of path variables. Some MVC frameworks do support them, for example Struts or Spring MVC.

For a servlet point of view, an URL is :

scheme://host.domain/context_path/servlet_path/path_info?parameters

where any of the parts (starting from context path may be null)

Spec for servlet 3.0 states :

  • Context Path: The path prefix associated with the ServletContext that this servlet is a part of. If this context is the “default” context rooted at the base of the Web server’s URL name space, this path will be an empty string. Otherwise, if the context is not rooted at the root of the server’s name space, the path starts with a / character but does not end with a / character.
  • Servlet Path: The path section that directly corresponds to the mapping which activated this request. This path starts with a ’/’ character except in the case where the request is matched with the ‘/*’ or ““ pattern, in which case it is an empty string.
  • PathInfo: The part of the request path that is not part of the Context Path or the Servlet Path. It is either null if there is no extra path, or is a string with a leading ‘/’.

The following methods exist in the HttpServletRequest interface to access this information:

  • getContextPath
  • getServletPath
  • getPathInfo

It is important to note that, except for URL encoding differences between the request URI and the path parts, the following equation is always true:

requestURI = contextPath + servletPath + pathInfo

That means that you just have to use @WebServlet(urlPatterns={"/posts"}), and then decode by hands the pathInfo part to extract commands and parameters



回答2:

I think you cannot do so using only the @WebServlet annotation. The urlPatterns only acts as a directive to the Servlet to indicate which url patterns should attend. And as you can see by this docs https://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebServlet.html the value is just the case when urlPatterns is one string instead of an array of them. As brso05 stated, you will need to parse from the request your parameters.