Monday, August 4, 2008

Action, ActionServlet, ActionMappings and Other Struts Stuff Explained in a Simple Tutorial

Of Actions and ActionServlets

The ActionServlet is what you might call a monolithic servlet. Every single request that gets sent to our Struts application goes through the ActionServlet first.

The ActionServlet is responsible for figuring out exactly what the client is requesting, and then the ActionServlet invokes a special object called an Action class. The Action class implements the logic required to fulfill the clients request.

The Action class is what the developers are required to code.

In many ways the Action class looks like a Servlet, although instead of having a doPost or doGet method, it has a special method called perform or execute. Like the doPost and doGet method of a Servlet, the perform/execute method of the action class is passes an HttpServletRequest (request) object and an HttpServletResponse (response) object. Anything you want to know about the client is buried inside the request object. Anything you want to do to the client, such as planting a cookie on their hard drive, is done using the response object.

The job of the Action class is to implement the logic required to fulfill the client request, and then figure out which JSP page should be used to generate html to be displayed in the client's browser.

A quick look at the syntax of an Action class demonstrates programatically the mechanics of the Action class:


public class TryLingualAction extends Action {

public ActionForward execute(

ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws Exception {

ActionErrors errors = new ActionErrors();

ActionForward forward = new ActionForward();

try {

String language =

request.getLocale().getDisplayLanguage();

if (language.equals("French")) {

forward = mapping.findForward("frenchpage");

}

if (language.equals("Spanish")) {

forward = mapping.findForward("spanishpage");

}

if (language.equals("English")) {

forward = mapping.findForward("englishpage");

}

} catch (Exception e) {

errors.add("name", new ActionError("id"));

}

return (forward);

}

}


Exploring the Code

Anything we want to know about the client, we can obtain through the request (HttpServletRequest) object.

The method call ‘request.getLocale()’ returns a special object called a Locale object. From this object we call the getDisplayLanguage() that returns the preferred language of the client in the form of a text string such a “French”, “Spanish” or “Engligh”. This information is sent behind the scenes from the browser to the server in the form of magical messages know as 'headers.'

Once we have figured out the preferred language of the user, we forward to an appropriate JSP for generating display.

No comments: