I'm trying to write a web app that needs to expose some methods that I'm going to us开发者_运维知识库e with ajax. I can make one servlet to route all incoming requests, or I can make multiple servlets, one for each request type. Something like:
public class ServletMain extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException
{
// parse the path and figure out which service call was made.
}
}
// web.xml
<servlet-mapping>
<servlet-name>SerlvetMain</servlet-name>
<url-pattern>/foo/a</url-pattern>
<url-pattern>/foo/b</url-pattern>
<url-pattern>/foo/c</url-pattern>
</servlet-mapping>
or:
public class ServletA extends HttpServlet;
public class ServletB extends HttpServlet;
public class ServletC extends HttpServlet;
// web.xml
<servlet-mapping>
<servlet-name>SerlvetA</servlet-name>
<url-pattern>/foo/a</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SerlvetB</servlet-name>
<url-pattern>/foo/b</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SerlvetC</servlet-name>
<url-pattern>/foo/c</url-pattern>
</servlet-mapping>
just wondering if we can do whatever we want, or if there's some rule to how to structure this kind of stuff?
Thanks
If you really intend to do this with "plain vanilla" Servlet API instead of a more suited REST API like JAX-RS (i.e, JSR311 with Jersey as reference implementation), then I recommend to go for the Front Controller pattern as depicted in your first example. That's more nicely abstracted than a web.xml
polluted with all possible url-pattern
entries.
Basically, just have a single Servlet which intercepts on all requests, grabs the pathinfo by HttpServletRequest#getPathInfo()
and determine the desired action accordingly based on a combination of the request method and pathinfo.
At least, try to look how they did it with Jersey (with the holy annotations!) and try to do the same. Or, better, just don't reinvent the wheel and use it ;)
精彩评论