How to use @WebServlet to accept arguments (using the RESTFul method)?

Suppose 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 @WebServlet servlet @WebServlet for this? I am researching value and urlPatterns , but I don't understand how to do this. For instance,

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

gives me some result, but how to use it? In addition, request.getPathInfo() seems to return a wildcard value, but what if I need more parameters, for example in http://http://myserver/myapplication/posts/<id>/delete/<force> ?

+1
source share
2 answers

In the servlet specification, you have no concept of path variables. Some MVC environments support them, such as Struts or Spring MVC.

For the servlet point, the URL is:

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

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

Specification for Servlet 3.0:

  • Context Path: The path prefix associated with the ServletContext that the Servlet is part of. If this context is a β€œstandard” context, rooted in the web server namespace, this path will be an empty string. Otherwise, if the context is not rooted in the root namespace of the servers, the path starts with / but does not end with the / character.
  • Servlet path: a section of the path that directly corresponds to the mapping that activated this request. This path starts with the character /, unless the request matches the pattern "/ * or", in which case it is an empty string.
  • PathInfo: part of the request path that is not part of the Context path or Servlet path. This is either null if there is no additional path, or a line with a leading "/.

In the HttpServletRequest interface, the following methods exist for accessing this information:

  • getContextPath
  • getServletPath
  • getPathInfo

It is important to note that, with the exception of differences in URL encoding between the URI request and parts of the path, the following equation is always true:

 requestURI = contextPath + servletPath + pathInfo 

This means that you just need to use @WebServlet(urlPatterns={"/posts"}) and then decode the pathInfo part with your hands to retrieve commands and parameters

+7
source

I think you cannot do this using only the @WebServlet annotation. UrlPatterns acts only as a directive for the servlet to indicate which url patterns should be present. And as you can see from these documents https://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebServlet.html , this value matters when urlPatterns is a single row, not an array from them. As stated in brso05, you will need to parse the request parameters.

+1
source

All Articles