Question

What I'm looking for is some sort of class or annotation I can add to Java classes that are dedicated to handling specific requests, and having URLs map to these based on their name. For example, have the URL ".../api/GetContactsRequest" map to a handler named GetContactsRequest (or 404 if no such handler exists). I know I could write servlets and map each URL to each servlet, but I figure the less boilerplate routing code/configuration, the better! These will mostly be application request handlers, communicating using JSON. I haven't figured out how I'll be handling static requests, but I'll most likely just be sending a big web application at the user that navigates itself or something.

For background, I'm using the Google App Engine so I have access to yaml configurations and their servlet APIs. So is there a standard way of doing this with either the Java servlet APIs or the Google App Engine-specific framework? I've only ever used specific Java servlet frameworks like Apache and stuff before, which were all already built by the time I started working on them, so I really don't know what there is to use with this environment. I'm also new to this all in general, and having trouble wading through what Servlets, Services, Filters, Listeners, and Handlers all are, and which is best for this simple routing behavior that I want/need. I'm worried I'll pick the wrong one, or don't even know of the one that would suit my needs.

Was it helpful?

Solution

This is what JAX-RS does - not exactly class name mapping, but mapping via annotations. See some of the features.

There are several implementations, personally I use RESTEasy - it works flawlessly on GAE. Additionally I use Jackson (comes with RESTEasy) to produce JSON.

If you need to produce html then look at htmleasy - it's a thin layer on top of RESTEasy enabling use of different html templating libraries. It'll help you separate logic from presentation.

EDIT:

If you really want to avoid using standard libs and writing something on your own, then write a servlet filter that inspects the request and forwards it to your servlet (or invoke custom code):

public class ForwardFilter implements Filter {

    @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {

        if(request.getRequestURI().equals("/some/path")){
            request.getRequestDispatcher("/path/where/servlet/registered").forward(request, response);
            return; // prevents normal request processing

        }

        // you need this for normal request path
        filterChain.doFilter(request, response);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top