Skip navigation

Category Archives: Java

In any modern web app, you probably want to have really cool and simple URLs like how WordPress does for your permalinks. E.g., the permalink for this posting is

https://bobobobo.wordpress.com/2008/05/04/how-do-i-design-a-simple-front-controller/

MUCH better than the typical MSDN type urls:

http://msdn.microsoft.com/en-us/library/52cs05fz.aspx
http://msdn.microsoft.com/en-us/library/d06h2x6e.aspx
http://msdn.microsoft.com/en-us/library/bb385954.aspx

Do you think when I complete this posting and publish it, WordPress will ACTUALLY PUT A FILE at https://bobobobo.wordpress.com/2008/05/04/how-do-i-design-a-simple-front-controller/?

NO you dummy!!

Anytime you see REALLY simple urls like http://www.website.com/PersonsUsername/ most likely what is happening there is the web application is using something called REQUEST MAPPING. You do REQUEST MAPPING using what is called a FRONT CONTROLLER.

The FRONT CONTROLLER works to INTERPRET requests for specific URI’s AS requests to OTHER pages, engines, and so on.

Give this a watch.

First, NOTICE how simple that uri is? In case you didn’t follow the link through, its http://cakephp.org/screencasts/view/3.

So CakePHP a front controller to do “request mapping!” WATCH THE VIDEO to get an idea, dude.

ANYWAY, how do you create a really simple front-controller and do request mapping from a Java servlet?

Just create a regular servlet, then make the web.xml entry for it something like this:

<servlet>
  <servlet-name>member</servlet-name>
  <servlet-class>member</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>member</servlet-name>
  <url-pattern>/member/*</url-pattern>
</servlet-mapping>

NOTICE the /member/* for the <url-pattern>? THAT means that ANY requests that come in with the pattern http://www.my.server.com/member/WHATEVER will AUTOMATICALLY be mapped down into the “member” servlet.

So the “member” servlet class might look something like this:

public class member extends HttpServlet
{
  protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    String requestURI = request.getRequestURI();  // if the user hit
    // http://www.my.site.com/member/BOB then the REQUEST URI looks like
    // /member/BOB
    // All I'm going to do now is get everything after the last slash,
    // and that is what will tell me which member profile is desired:
    String desiredUserProfile = requestURI.substring( requestURI.lastIndexOf("/") + 1 );

    // work with desiredUserProfile to produce page output, whatever.
  }
}

Get the idea?

See also:

Java:
http://java.sun.com/blueprints/corej2eepatterns/Patterns/FrontController.html

PHP:
http://www.phpwact.org/pattern/front_controller

Apache Server:

mod_rewrite