[SOLVED] [Java/JSP] I need an Action controller example :(

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

[SOLVED] [Java/JSP] I need an Action controller example :(

Post by Chris Corbyn »

I'm struggling to find a simple example of how to do the following with Servlets/JSP:

1. Create a simple composite view (JSP file) used on each page:

Code: Select all

------------------------
      HEADER
------------------------


  {CONTENT}


------------------------
    FOOTER
------------------------
2. Create a FrontController which reads "module" and "action" arguments from the request then loads an action controller for that module and runs the relevant action in it.

3. Front controller loads JSP for the current module along with the overall layout JSP (header+footer) the combines the two and displays it.

In Pseudo code I'm just thinking extremely basic along the lines of this extremely hackish messy code (which doesn't actually work):

Code: Select all

/**
 * The FrontController which all web requests communicate to.
 * The front controller delegates requests to individual action controllers.
 */

package org.w3style.controllers;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class FrontController extends HttpServlet {
  
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    
    processRequest(req, resp);
  }

  public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    processRequest(req, resp);
  }
  
  public void processRequest(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  
    String view = null;
    try {
      String module = "Home"; //Would come from URL
      String action = "Index"; //Would come from URL
      //Get the class for the action controller
      Class actionClass = Class.forName("org.w3style.controllers." + module + "Actions");
      //Create a new instance of the action controller
      ActionController ac = actionClass.newInstance();
      //Execute the action in it
      actionClass.getDeclaredMethod("execute" + action,
        new Class["HttpServletRequest", "HttpServletResponse"]).invoke(ac, null);
      //Construct a path to the view for this action
      view = "/view/" + module + "/" + action + ".jsp";
    } catch (Exception e) {
      //dump some error report
    }
    //Store the path to the view so layout.jsp can include it
    req.setAttribute("includeFile", view);
    ServletContext app = getServletContext();
    RequestDispatcher disp;
    //Dispatch to main template file, includes the header + footer etc
    disp = app.getRequestDispatcher("/view/_layout/layout.jsp");
    disp.forward(req, resp);
  }
}
I've been searching for ages for decent tutorials on how to handle action controllers in Java, and also how to deal with a composite view but I just keep coming back to these articles which I don't really understand because my experience with servlets amounts to just a few days.

http://java.sun.com/blueprints/corej2ee ... oller.html
http://java.sun.com/blueprints/patterns ... eView.html
http://java.sun.com/blueprints/guidelin ... tier5.html

Does anyone have any links to easier to follow tutorials which use code to demonstrate the principles rather than a whole load of "waffle" about advanced Java stuff? :(
Last edited by Chris Corbyn on Fri Jul 06, 2007 12:35 pm, edited 1 time in total.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

OK, so I took my pseudo example and wrote it. It works but I hate it with a passion. It just feels so clumsy and amateur... especially since it so heavily relies on reflection.

Code: Select all

/**
 * The FrontController which all web requests communicate to.
 * The front controller delegates requests to individual action controllers.
 */

package org.w3style.controllers;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * FrontController class.
 */
public class FrontController extends HttpServlet {
  /**
   * Handle GET requests over HTTP.
   * @param HttpServletRequest The request
   * @param HttpServletResponse The response
   * @throws ServletException
   * @throws IOException
   */
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    
    String view = null;
    try {
      String module = "Home"; //Would come from URL
      String action = "Index"; //Would come from URL
      Class actionClass = Class.forName("org.w3style.controllers." + module + "Actions");
      ActionController ac = (ActionController) actionClass.newInstance();
      Class[] params = { Class.forName("javax.servlet.http.HttpServletRequest"),
        Class.forName("javax.servlet.http.HttpServletResponse") };
      
      Object[] args = { req, resp };
      actionClass.getDeclaredMethod("execute" + action, params).invoke(ac, args);
      view = "/view/" + module + "/" + action + ".jsp";
    } catch (Exception e) {
      throw new ServletException("Doh!" + e);
    }
    req.setAttribute("includeFile", view);
    ServletContext app = getServletContext();
    RequestDispatcher disp;
    disp = app.getRequestDispatcher("/view/_layout/layout.jsp");
    disp.forward(req, resp);
  }
}
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Sorry to repeat-post. I've decided I'm going to adopt Struts in future, but since I'm just learning to do things wrong (the best way to learn :P) right now I'll finish my project the route I'm going. After doing a bit of research into Struts it turns out that it also uses reflection. With a bit of cleaning up and refactoring I'm not a million miles off the mark :)

Cheers, I'm done now.
Post Reply