Thursday, August 22, 2013

Struts 1.x Web Form Components Example 01

Struts 1.x Web Form Components Example 01 

Struts 1.x Web Form Components Example

In this example work with “html” tags, “bean” tags and “logic” tags. Below list is the used tags for this exercise.

html” tags -
1. HTML text box input field with Struts <html:text> tag
2. HTML radio option with Struts <html:radio> tag.
3. HTML select option (drop down box) with Struts <html:select> and <html:option> tag
4. HTML check box option with Struts <html:checkbox> tag
5. HTML text area field Struts <html:textarea> tag
6. <html:reset> button option
7. <html:submit> button option

bean” tags -
1. <bean:message>
2. <bean:write>

logic” tags -
1. <logic:present>
2. <logic:equal>
3. <logic:notEmpty>
4. <logic:iterate>

Please note there are lot of tags related to the “html”, “bean” and “logic”. Here show you few tags out from those which are used to complete this application.

You can import these tag libraries ( “html”, “bean”, “logic” ) by using below ways.
  1. Call relevant tld by save the tld inside your WEB-INF.
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html"%>
  1. Call the apache.org
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>


Step - 1.0 Create Directory Structure

Create the folder structure and add struts libraries under the lib folder which is inside the WEB-INF.
If plan to call the tld from the project itself then add the tlds to the WEB-INF.

 

Step - 2.0 Create Action Form

Create a java class called “MainForm.java” by extending struts Action Form. This is use to hold the data later. Also this example we use the form validation by using ActionErrors validate() method.

package com.form;

import java.io.Serializable;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class MainForm extends ActionForm implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
private String sex; //radio button
private String ageGroup; //drop down
private String educationDiploma; //check box
private String educationDegree; //check box
private String educationMasters; //check box
private String description; //text area
private ArrayList<String> messageList; //logic:iterate option

//TODO generate getter and setter methods ...

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if( null == getFirstName() || getFirstName().compareToIgnoreCase("")==0 ){
ActionMessages messages = new ActionMessages();
messages.add("display.error.firstname", new ActionMessage("error.firstname.required"));
errors.add(messages);
}
if( null == getLastName() || getLastName().compareToIgnoreCase("")==0 ){
ActionMessages messages = new ActionMessages();
messages.add("display.error.lastname", new ActionMessage("error.lastname.required"));
errors.add(messages);
}
if( null == getSex() || getSex().compareToIgnoreCase("")==0 ){
ActionMessages messages = new ActionMessages();
messages.add("display.error.sex", new ActionMessage("error.sex.required"));
errors.add(messages);
}
if( null == getAgeGroup() || getAgeGroup().compareToIgnoreCase("")==0 || getAgeGroup().equalsIgnoreCase("0") ){
ActionMessages messages = new ActionMessages();
messages.add("display.error.agegroup", new ActionMessage("error.agegroup.required"));
errors.add(messages);
}
if( null == getEducationDiploma() && null == getEducationDegree() && null == getEducationMasters() ){
ActionMessages messages = new ActionMessages();
messages.add("display.error.education", new ActionMessage("error.education.required"));
errors.add(messages);
}else{
if( null != getEducationDiploma() && getEducationDiploma().compareToIgnoreCase("")==0){
ActionMessages messages = new ActionMessages();
messages.add("display.error.education", new ActionMessage("error.education.required"));
errors.add(messages);
}
if( null != getEducationDegree() && getEducationDegree().compareToIgnoreCase("")==0){
ActionMessages messages = new ActionMessages();
messages.add("display.error.education", new ActionMessage("error.education.required"));
errors.add(messages);
}
if( null != getEducationMasters() && getEducationMasters().compareToIgnoreCase("")==0){
ActionMessages messages = new ActionMessages();
messages.add("display.error.education", new ActionMessage("error.education.required"));
errors.add(messages);
}
}
if( null == getDescription() || getDescription().compareToIgnoreCase("")==0 ){
ActionMessages messages = new ActionMessages();
messages.add("display.error.description", new ActionMessage("error.description.required"));
errors.add(messages);
}

return errors;
}
    @Override
    public void reset(ActionMapping mapping, HttpServletRequest request) {
      // reset properties
      this.firstName = "";
      this.lastName = "";
      this.sex = "";
      this.ageGroup = "0";
      this.description = "";
   }
}

Step - 3.0 Create Action Class

Create a class called “MainAction.java” by extending the Action.

package com.action;

import java.util.ArrayList;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.form.MainForm;

public class MainAction extends Action{

  public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{
    
     ArrayList<String> msgList = new ArrayList<String>();
     msgList.add("To complete the Registration please do the below payments.");
     msgList.add("Application Fee : Rs.1000.00");
     msgList.add("Medical test Fee : Rs.250.00");
     msgList.add("Legal Advise Fee : Rs.750.00");
     msgList.add("Documentation Fee : Rs.50.00");
     MainForm mainForm = (MainForm)form;
     mainForm.setMessageList(msgList);
     return mapping.findForward("success");
  }
}

Step - 4.0 Create JSP view page

Create jsp called “main.jsp” and “mainDetails.jsp”. Other than that create a resource file to call the property values ( common.properties ) and create a css files to call the styles ( myStyles.css ).

4.1 main.jsp -

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Main Page</title>
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/myStyles.css">
</head>
<body>
<html:form action="/ExecuteMain">
<div id="divHeader" class="divHeaderTable">
&nbsp;&nbsp;<h3><bean:message key="label.user.registration"/></h3>
</div>
<div id="content" class="divTable">
<!-- Text Box -->
<div class="divRow">
<div class="divColumn"><bean:message key="label.firstname"/></div>
<div class="divColumn"><html:text property="firstName" size="20" maxlength="20"></html:text></div>
</div>
<div class="divRow">
<div class="divColumn"><bean:message key="label.lastname"/></div>
<div class="divColumn"><html:text property="lastName" size="20" maxlength="20"></html:text></div>
</div>
<!-- Radio Button -->
<div class="divRow">
<div class="divColumn"><bean:message key="label.sex"/></div>
<div class="divColumn">
<html:radio property="sex" value="Male"/>&nbsp;<bean:message key="label.sex.male"/>&nbsp;&nbsp;
<html:radio property="sex" value="Female"/>&nbsp;<bean:message key="label.sex.female" />
</div>
</div>
<!-- Drop down list -->
<div class="divRow">
<div class="divColumn"><bean:message key="label.age.group"/></div>
<div class="divColumn">
<html:select property="ageGroup">
<html:option value="0"><bean:message key="label.age.group.select"/></html:option>
<html:option value="21-30">21-30</html:option>
<html:option value="31-40">31-40</html:option>
<html:option value="41-50">41-50</html:option>
<html:option value="51-60">51-60</html:option>
</html:select>
</div>
</div>
<!-- Check Box -->
<div class="divRow">
<div class="divColumn"><bean:message key="label.education"/></div>
<div class="divColumn">
<bean:message key="label.education.diploma"/>&nbsp;:&nbsp;<html:checkbox property="educationDiploma"></html:checkbox>
<br>
<bean:message key="label.education.degree"/>&nbsp;:&nbsp;<html:checkbox property="educationDegree"></html:checkbox>
<br>
<bean:message key="label.education.masters"/>&nbsp;:&nbsp;<html:checkbox property="educationMasters"></html:checkbox>
</div>
</div>
<!-- text area -->
<div class="divRow">
<div class="divColumn"><bean:message key="label.description"/></div>
<div class="divColumn">
<html:textarea property="description" cols="40" rows="10"></html:textarea>
</div>
</div>
<!-- Buttons -->
<div class="divRow">
<div class="divColumn columnTopPadding"><html:reset><bean:message key="label.button.reset"/></html:reset></div>
<div class="divColumn columnTopPadding"><html:submit><bean:message key="label.button.submit"/></html:submit></div>
</div>
<!-- Form Errors -->
<div class="divRow">
<div class="columnTopPadding errorfontred">
<div class="divColumn columnTopPadding">
<br><html:errors property="display.error.firstname"/>
<br><html:errors property="display.error.lastname"/>
<br><html:errors property="display.error.sex"/>
<br><html:errors property="display.error.agegroup"/>
<br><html:errors property="display.error.education"/>
<br><html:errors property="display.error.description"/>
</div>
</div>
</div>
</div>
</html:form>
</body>
</html>

4.2 mainDetails.jsp -

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome Page</title>
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/myStyles.css">
</head>
<body>
<div id="divHeader" class="divHeaderTable">
&nbsp;&nbsp;<h3><bean:message key="label.user.registration"/></h3>
</div>
<div id="content" class="divTable columnTopPadding">
<div class="divRow">
<div class="divColumn"><bean:message key="label.firstname"/></div>
<div class="divColumn fontcolorblue"><bean:write name="MainForm" property="firstName"/></div>
</div>
<div class="divRow">
<div class="divColumn"><bean:message key="label.lastname"/></div>
<div class="divColumn fontcolorblue"><bean:write name="MainForm" property="lastName"/></div>
</div>
<div class="divRow">
<div class="divColumn"><bean:message key="label.sex"/></div>
<div class="divColumn fontcolorblue"><bean:write name="MainForm" property="sex"/></div>
</div>
<div class="divRow">
<div class="divColumn"><bean:message key="label.age.group"/></div>
<div class="divColumn fontcolorblue"><bean:write name="MainForm" property="ageGroup"/></div>
</div>
<div class="divRow columnTopPadding">
<div class="divColumn"><bean:message key="label.education"/></div>
<div class="divColumn fontcolorblue">
<logic:present name="MainForm" property="educationDiploma">
<logic:equal name="MainForm" property="educationDiploma" value="on"><bean:message key="label.education.diploma"/></logic:equal>
</logic:present>
<br>
<logic:present name="MainForm" property="educationDegree">
<logic:equal name="MainForm" property="educationDegree" value="on"><bean:message key="label.education.degree"/></logic:equal>
</logic:present>
<br>
<logic:present name="MainForm" property="educationMasters">
<logic:equal name="MainForm" property="educationMasters" value="on"><bean:message key="label.education.masters"/></logic:equal>
</logic:present>
</div>
</div>
<br>
<div class="divRow columnTopPadding">
<div class="divColumn"><bean:message key="label.description"/></div>
<div class="divColumn fontcolorblue"><bean:write name="MainForm" property="description"/></div>
</div>
<div class="columnTopPadding">
<br><br>------------------------------------------------------------------------------------------------------<br>
<logic:notEmpty name="MainForm" property="messageList">
<logic:iterate property="messageList" id="listOfMsg" name="MainForm">
<bean:write name="listOfMsg"/><br>
</logic:iterate>
</logic:notEmpty>
</div>
</div>
</body>
</html>

4.3 common.properties -

#error messages
error.firstname.required = Please enter the First Name.
error.lastname.required = Please enter the Last Name.
error.sex.required = Please select the Sex.
error.agegroup.required = Please select the Age Group.
error.education.required = Please select the Educational Level.
error.description.required = Please describe your self.

#label messages
label.user.registration = User Registration Form
label.firstname = First Name
label.lastname = Last Name
label.sex = Sex
label.sex.male = Male
label.sex.female = Female
label.age.group = Age Group
label.age.group.select = -- Select the Age Group --
label.education = Education
label.education.diploma = Diploma
label.education.degree = Bachelor Degree
label.education.masters = Masters Degree
label.description = Description

#button label messages
label.button.submit = Submit
label.button.reset = Reset

4.4 myStyles.css -

body{
background-color: aqua; font-family: Verdana;
font-size: 12px; font-style: normal; color: black;
}
.divHeaderTable{
width: 50%; padding-bottom:5px; display:block;
}
.divHeaderRow{
width: 50%; /* add extra that you want to for header column */
display:block; height:105px;
}
.divHeaderColumn{
float: left; width: 33%; display:block;
}
.divTable{
width: 50%; display:block; padding-top:10px;
padding-bottom:10px; padding-right:10px; padding-left:10px;
}
.divRow{
width: 99%; display:block; padding-top:10px; padding-bottom:10px;
}
.divColumn{
float: left; width: 48%; display:block;
}
.columnTopPadding{
padding-top: 10px;
}
.fontcolorblue{
color: blue;
}
.errorfontred{
color: red;
}

Step - 5.0 Create struts-config.xml

Create a struts-config.xml file for the Struts configuration details, and put it into the WEB-INF/config folder.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="MainForm" type="com.form.MainForm"/>
</form-beans>
<action-mappings>
<action path="/MainPage"
type="org.apache.struts.actions.ForwardAction"
parameter="/WEB-INF/jsp/main.jsp"/>
<action path="/ExecuteMain" type="com.action.MainAction" name="MainForm"
validate="true" input="/WEB-INF/jsp/main.jsp">
<forward name="success" path="/WEB-INF/jsp/mainDetails.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.resource.common"/>
</struts-config>


Step - 6.0 The web application deployment descriptor ( web.xml )

In web.xml file, configure the Struts ActionServlet instance and map it with url-pattern “*.do”, so that the container is aware of all the “*.do” pattern will redirect to Struts ActionServlet.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>WebFormComponenetExample</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/config/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

Step - 7.0 Run the application on server and out put will be

http://localhost:8080/StrutsWebFormComponenetExample/MainPage.do

Validation -

 

After Submit -