Struts 2
Tag: A small piece of code executed from within JSP, FreeMarker, or Velocity.
Template: A bit of code, usually written in FreeMarker, that can be rendered by certain tags (HTML tags)
Theme: A collection of templates packaged together to provide common functionality
Tags:
Generic : control: if, iterator, append... data: a, action, bean, date, include...
UI : Form: checkbox, radio, textarea... nonForm: actionerror, actionmessage... ajax: a, bind, autocompleter...
Login.java
public class Login extends ActionSupport {
public String execute() throws Exception {
if (isInvalid(getUsername())) return INPUT;
if (isInvalid(getPassword())) return INPUT;
return SUCCESS;
}
private boolean isInvalid(String value) {
return (value == null || value.length() == 0);
}
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
LoginValidation.xml
<validators>
<field name="username">
<field-validator type="requiredstring">
<message key="requiredstring"/>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message key="requiredstring"/>
</field-validator>
</field>
</validators>
HelloWorld.java
public class HelloWorld extends ActionSupport {
public String execute() throws Exception {
setMessage(getText(MESSAGE));
return SUCCESS;
}
/**
* Provide default valuie for Message property.
*/
public static final String MESSAGE = "HelloWorld.message";
/**
* Field for Message property.
*/
private String message;
/**
* Return Message property.
*
* @return Message property
*/
public String getMessage() {
return message;
}
/**
* Set Message property.
*
* @param message Text to display on HelloWorld page.
*/
public void setMessage(String message) {
this.message = message;
}
}
package.properties
HelloWorld.message= Struts is up and running ...
requiredstring = ${getText(fieldName)} is required.
password = Password
username = User Name
Missing.message = This feature is under construction. Please try again in the next interation.
example.xml
<struts>
<package name="example" namespace="/example" extends="struts-default">
<action name="HelloWorld" class="example.HelloWorld">
<result>/example/HelloWorld.jsp</result>
</action>
<action name="Login_*" method="{1}" class="example.Login">
<result name="input">/example/Login.jsp</result>
<result type="redirect-action">Menu</result>
</action>
<action name="*" class="example.ExampleSupport">
<result>/example/{1}.jsp</result>
</action>
<!-- Add actions here -->
</package>
</struts>
struts.xml
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<include file="example.xml"/>
<!-- Add packages here -->
</struts>
HelloWorld.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title><s:text name="HelloWorld.message"/></title>
</head>
<body>
<h2><s:property value="message"/></h2>
<h3>Languages</h3>
<ul>
<li>
<s:url id="url" action="HelloWorld">
<s:param name="request_locale">en</s:param>
</s:url>
<s:a href="%{url}">English</s:a>
</li>
<li>
<s:url id="url" action="HelloWorld">
<s:param name="request_locale">es</s:param>
</s:url>
<s:a href="%{url}">Espanol</s:a>
</li>
</ul>
</body>
</html>
Login.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Sign On</title>
</head>
<body>
<s:form action="Login">
<s:textfield key="username"/>
<s:password key="password" />
<s:submit/>
</s:form>
</body>
</html>
web.xml
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
URL:
http://localhost:8080/example/HelloWorld.action
Struts 1
public final class SubscriptionForm extends ActionForm {
// --------------------------------------------------- Instance Variables
/**
* The maintenance action we are performing (Create or Edit).
*/
private String action = "Create";
/**
* The host name.
*/
private String host = null;
// ----------------------------------------------------------- Properties
/**
* Return the maintenance action.
*/
public String getAction() {
return (this.action);
}
/**
* Set the maintenance action.
*
* @param action The new maintenance action.
*/
public void setAction(String action) {
this.action = action;
}
// --------------------------------------------------------- Public Methods
/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.action = "Create";
}
/**
* Validate the properties that have been set from this HTTP request,
* and return an <code>ActionErrors</code> object that encapsulates any
* validation errors that have been found. If no errors are found, return
* <code>null</code> or an <code>ActionErrors</code> object with no
* recorded error messages.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ((host == null) || (host.length() < 1))
errors.add("host",
new ActionError("error.host.required"));
return (errors);
}
}
public final class SaveRegistrationAction extends Action {
// ----------------------------------------------------- Instance Variables
/**
* The <code>Log</code> instance for this application.
*/
private Log log =
LogFactory.getLog("org.apache.struts.webapp.Example");
// --------------------------------------------------------- Public Methods
/**
* Process the specified HTTP request, and create the corresponding HTTP
* response (or forward to another web component that will create it).
* Return an <code>ActionForward</code> instance describing where and how
* control should be forwarded, or <code>null</code> if the response has
* already been completed.
*
* @param mapping The ActionMapping used to select this instance
* @param actionForm The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
// Extract attributes and parameters we will need
Locale locale = getLocale(request);
MessageResources messages = getResources(request);
HttpSession session = request.getSession();
RegistrationForm regform = (RegistrationForm) form;
String action = regform.getAction();
if (action == null) {
action = "Create";
}
UserDatabase database = (UserDatabase)
servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
if (log.isDebugEnabled()) {
log.debug("SaveRegistrationAction: Processing " + action +
" action");
}
// Is there a currently logged on user (unless creating)?
User user = (User) session.getAttribute(Constants.USER_KEY);
if (!"Create".equals(action) && (user == null)) {
if (log.isTraceEnabled()) {
log.trace(" User is not logged on in session "
+ session.getId());
}
return (mapping.findForward("logon"));
}
// Was this transaction cancelled?
if (isCancelled(request)) {
if (log.isTraceEnabled()) {
log.trace(" Transaction '" + action +
"' was cancelled");
}
session.removeAttribute(Constants.SUBSCRIPTION_KEY);
return (mapping.findForward("success"));
}
// Validate the transactional control token
ActionErrors errors = new ActionErrors();
if (log.isTraceEnabled()) {
log.trace(" Checking transactional control token");
}
if (!isTokenValid(request)) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.transaction.token"));
}
resetToken(request);
// Validate the request parameters specified by the user
if (log.isTraceEnabled()) {
log.trace(" Performing extra validations");
}
// Report any errors we have discovered back to the original form
if (!errors.isEmpty()) {
saveErrors(request, errors);
saveToken(request);
return (mapping.getInputForward());
}
return (mapping.findForward("success"));
}
}
Struts-config.xml :
<struts-config>
<!-- ========== Data Source Configuration =============================== -->
<!--
<data-sources>
<data-source>
<set-property property="autoCommit"
value="false"/>
<set-property property="description"
value="Example Data Source Configuration"/>
<set-property property="driverClass"
value="org.postgresql.Driver"/>
<set-property property="maxCount"
value="4"/>
<set-property property="minCount"
value="2"/>
<set-property property="password"
value="mypassword"/>
<set-property property="url"
value="jdbc:postgresql://localhost/mydatabase"/>
<set-property property="user"
value="myusername"/>
</data-source>
</data-sources>
-->
<!-- ========== Form Bean Definitions =================================== -->
<form-beans>
<!-- Logon form bean -->
<form-bean name="logonForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="username" type="java.lang.String" />
<form-property name="password" type="java.lang.String" />
</form-bean>
<!-- Subscription form bean -->
<form-bean name="subscriptionForm"
type="org.apache.struts.webapp.example.SubscriptionForm" />
</form-beans>
<!-- ========== Global Forward Definitions ============================== -->
<global-forwards>
<forward name="logoff" path="/logoff.do" />
<forward name="logon" path="/logon.jsp" />
<forward name="success" path="/mainMenu.jsp" />
</global-forwards>
<!-- ========== Action Mapping Definitions ============================== -->
<action-mappings>
<!-- Edit mail subscription -->
<action path="/editSubscription"
type="org.apache.struts.webapp.example.EditSubscriptionAction"
attribute="subscriptionForm" scope="request" validate="false">
<forward name="failure" path="/mainMenu.jsp" />
<forward name="success" path="/subscription.jsp" />
</action>
<!-- Process a user logoff -->
<action path="/logoff"
type="org.apache.struts.webapp.example.LogoffAction">
<forward name="success" path="/index.jsp" />
</action>
<!-- Process a user logon -->
<action path="/logon"
type="org.apache.struts.webapp.example.LogonAction" name="logonForm"
scope="session" input="logon">
<exception key="expired.password"
type="org.apache.struts.webapp.example.ExpiredPasswordException"
path="/changePassword.jsp" />
</action>
<!-- Save mail subscription -->
<action path="/saveSubscription"
type="org.apache.struts.webapp.example.SaveSubscriptionAction"
name="subscriptionForm" scope="request" input="subscription">
<forward name="subscription" path="/subscription.jsp" />
<forward name="success"
path="/editRegistration.do?action=Edit" />
</action>
<!-- Display the "walking tour" documentation -->
<action path="/tour" forward="/tour.htm"></action>
</action-mappings>
<!-- ========== Controller Configuration ================================ -->
<controller>
<!-- The "input" parameter on "action" elements is the name of a
local or global "forward" rather than a module-relative path -->
<set-property property="inputForward" value="true" />
</controller>
<!-- ========== Message Resources Definitions =========================== -->
<message-resources
parameter="org.apache.struts.webapp.example.ApplicationResources" />
<message-resources
parameter="org.apache.struts.webapp.example.AlternateApplicationResources"
key="alternate">
</message-resources>
<!-- ========== Plug Ins Configuration ================================== -->
<plug-in className="org.apache.struts.plugins.ModuleConfigVerifier" />
<plug-in
className="org.apache.struts.webapp.example.memory.MemoryDatabasePlugIn">
<set-property property="pathname" value="/WEB-INF/database.xml" />
</plug-in>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml" />
</plug-in>
</struts-config>
validation.xml :
<form-validation>
<!-- ========== Default Language Form Definitions ===================== -->
<formset>
<form name="logonForm">
<field property="username"
depends="required, minlength,maxlength">
<arg0 key="prompt.username" />
<arg1 key="${var:minlength}" name="minlength"
resource="false" />
<arg2 key="${var:maxlength}" name="maxlength"
resource="false" />
<var>
<var-name>maxlength</var-name>
<var-value>16</var-value>
</var>
<var>
<var-name>minlength</var-name>
<var-value>3</var-value>
</var>
</field>
<field property="password"
depends="required, minlength,maxlength" bundle="alternate">
<arg0 key="prompt.password" />
<arg1 key="${var:minlength}" name="minlength"
resource="false" />
<arg2 key="${var:maxlength}" name="maxlength"
resource="false" />
<var>
<var-name>maxlength</var-name>
<var-value>16</var-value>
</var>
<var>
<var-name>minlength</var-name>
<var-value>3</var-value>
</var>
</field>
</form>
<form name="registrationForm">
<field property="fromAddress" depends="required,email">
<arg0 key="prompt.fromAddress" />
</field>
<field property="fullName" depends="required">
<arg0 key="prompt.fullName" />
</field>
<field property="replyToAddress" depends="email">
<arg0 key="prompt.replyToAddress" />
</field>
<field property="username" depends="required">
<arg0 key="prompt.username" />
</field>
</form>
</formset>
</form-validation>