Monday, November 3, 2008

Struts Sample Code

HelloAction.java:

package ch18.hello;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.taglib.html.Constants;
import org.apache.struts.util.MessageResources;

public final class HelloAction extends Action {

public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {

MessageResources messages = getResources(request);

ActionErrors errors = new ActionErrors();
String person = (String) PropertyUtils.getSimpleProperty(form, "person");

String badPerson = "Atilla the Hun";

if (person.equals(badPerson)) {
errors.add("person",
new ActionError("error.message.required", badPerson ));
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
}

HelloModel hm = new HelloModel();
hm.setPerson(person);
hm.saveToPersistentStore();

request.setAttribute( Constants.BEAN_KEY,hm);

request.removeAttribute(mapping.getAttribute());

return (mapping.findForward("SayHello"));

}
}


HelloForm.java:
----------------------------------------

package ch18.hello;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public final class HelloForm extends ActionForm {

private String person = null;

public String getPerson() {

return (this.person);

}


public void setPerson(String person) {
this.person = person;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.person = null;
}


public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if ((person == null) || (person.length() < 1))
errors.add("person", new ActionError("ch18.hello.no.person.error"));

return errors;
}
}

HelloModel.java:
-----------------------------------

package ch18.hello;
public class HelloModel {

private String _person = null;

public String getPerson() {
return this._person;
}

public void setPerson(String person) {

this._person = person;

}

public void saveToPersistentStore() {


}
}


Constants.java:
------------------------------

package ch18.hello;

/* Constants to be used in the Hello World! Example*/


public final class Constants {

/**
* The application scope attribute under which our user database
* is stored.
*/
public static final String Hello_KEY = "ch18.hello";

}

No comments: