Question

I've created a abstract base class Page that figures out how to construct a dynamic web page. I'm trying to come up with a good way to generate a Page based off the GET request that comes in as a HttpServletRequest. For example...

public class RootServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {

        Page page = Page.generatePage(request);

        // do stuff with page and write back response
    }
}

In the generatePage() method, I somehow have to figure out what page is being requested, build the correct page, and then return an instance of it. But I'm not sure how to do this well... for example, I need to handle these kinds of URLs coming in:

http://example.com/       : build the default home page
http://example.com/ab123  : build the page corresponding to the given token "ab123"
http://example.com/about/ : build the "about" page
http://help.example.com/  : build the "help" page

Each of these "pages" extend the abstract base class Page so they know how to build themselves, but I'm not sure how to determine that the AboutPage needs to be built, or the HelpPage, as opposed to the default HomePage.

I'm using Apache Velocity as the template engine, so these Page objects really contain only the important information needed to generate that page, like which styles and scripts to use, and the relevant content to be displayed on the page.

I would think there are better ways to do this than to look at the end of the URL and see if "about" is a substring to build the AboutPage, for example. Any suggestions?

Was it helpful?

Solution

There are dozens of off the shelf tools frameworks that do this for you. In the very least I'd suggest Spring MVC which will work with velocity.

OTHER TIPS

Spring MVC has a great way to deal with this kind of stuff using controllers with annotated methods to handle the specific pattern that you want.

They have a great example application here:

https://github.com/SpringSource/spring-mvc-showcase

Anyway, it is not a good practice to build your pages using java code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top