Understanding Struts 2.0

EmployeeRegistrationForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<%@taglib uri="/struts-dojo-tags" prefix="sx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <sx:head />
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>EmployeeRegistrationForm</title>
        <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>
        <s:actionerror/>
    </head>    
    <body>
        <br><br><br><br>
        <table align="center">
            <tr>
                <s:if test="employee == null || employee.id == null ">
                    <th colspan="2" class="alignMiddle"><font size="4">Employee Registration Form</font></th>
                </s:if>
                <s:else>
                    <th colspan="2" class="alignMiddle"><font size="4">Employee Registration Edit Form</font></th>
                </s:else>
            </tr>
            <tr>
                <td colspan="2">&nbsp;</td>
            </tr>
            <tr>
                <td colspan="2">
                    <s:form name="studentregistrationForm" id="studentregistrationForm" method="post" action="insertOrUpdate" validate="false" >

                        <s:textfield name="employee.firstName" label="FIRST NAME" size="25" maxlength="15" value="%{employee.firstName}" />
                        <s:textfield name="employee.middleName" label="MIDDLE NAME" value="%{employee.middleName}" size="25" maxlength="15" />
                        <s:textfield name="employee.lastName" label="LAST NAME" value="%{employee.lastName}" size="25" maxlength="15" />
                        <s:radio name="employee.gender" label="GENDER" list="%{#{'m':'Male','f':'Female'}}" value="%{employee.gender}" />
                        <%--  <s:textfield name="birthDate" label="BIRTH DATE" size="10" />   --%>
                        <sx:datetimepicker name="employee.birthDate" label="BIRTH DATE" value="%{employee.birthDate}" displayFormat="dd/MM/yyyy" toggleType="fade" toggleDuration="500" />
                        <s:textarea name="employee.currentAddress" label="CURRENT ADDRESS" value="%{employee.currentAddress}" rows="4" cols="35"  />
                        <s:textarea name="employee.permenentAddress" label="PARMENENT ADDRESS" value="%{employee.permenentAddress}" rows="4" cols="35" />
                        <s:textfield name="employee.emailAddress" label="EMAIL ADDRESS" value="%{employee.emailAddress}" size="60" maxlength="50"/>
                        <s:textfield name="employee.mobileNo" label="MOBILE NO" size="20" maxlength="10" value="%{employee.mobileNo}" />
                        <s:textfield name="employee.landLineNo" label="LAND LINE NO" size="25" maxlength="15" value="%{employee.landLineNo}" />
                        <s:radio name="employee.incomeLevel" label="CURRENT INCOME LEVEL" list="%{#session.incomeLevels}" listKey="incomeLevelId" listValue="incomeLevelName" value="%{employee.incomeLevel}" />
                        <s:textfield  name="employee.expectedSalary" label="EXPECTED SALARY" value="%{employee.expectedSalary}" />
                        <s:select name="employee.programmingLanguagesKnown" label="PROGRAMMING LANGUAGES KNOWN" list="%{#session.programmingLanguagesKnownList}" listKey="programmingLanguageId" listValue="programmingLanguageName" headerKey="" headerValue="-- Select --" multiple="true" size="5" value="%{employee.programmingLanguagesKnown}"/>
                        <s:select name="employee.degreeId" label="HEIGHEST EDUCATIONAL QUALIFICATION" list="%{#session.heighestEducationalQualifications}"  headerKey="" headerValue="-- Select --" listKey="degreeId" listValue="degreeName" value="%{employee.degreeId}"/>
                        <s:select name="employee.city" list="%{#{}}" headerKey=""  headerValue="    -- Select --    " label="PREFFERD CITY" value="%{employee.city}">
                            <s:optgroup label="Gujarat" list="%{#session.gujaratCities}" />
                            <s:optgroup label="Madhyapradesh" list="%{#session.madhyaPradeshCities}" />
                            <s:optgroup label="Maharashtra" list="%{#session.maharashtraCities}" />
                            <s:optgroup label="Rajasthan" list="%{#session.rajasthanCities}" />
                        </s:select>
                        <s:checkboxlist name="employee.hobby" list="%{#session.hobbies}" listKey="hobbyId" listValue="hobbyName" label="HOBBY" value="%{employee.hobby}" />
                        <s:checkbox name="employee.condition" label="I AGREE TO ALL JOINING TERMS AND CONDITIONS" value="%{employee.condition}" />
                <tr>
                    <td colspan="2">&nbsp;</td>
                </tr>
                <tr>
                    <td align="center" colspan="2">
                        <s:if test="employee == null || employee.id == null ">
                            <input type="submit" value="REGISTER" class="butStnd" />&nbsp;
                        </s:if>
                        <s:else>
                            <input type="submit" value="EDIT" class="butStnd" />&nbsp;
                        </s:else>
                        <input type="reset" value="RESET" class="butStnd" />
                    </td>
                </tr>
                <s:hidden name="employee.id" value="%{employee.id}"/>
            </s:form>
        </td>
    </tr>
</table>
</body>
</html>

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    
<struts>
    <package name="default" extends="struts-default">
        <action name="setUpForInsertOrUpdate" method="setUpForInsertOrUpdate" class="learnstruts.demo.action.EmployeeAction">
            <interceptor-ref name="validation">
                <param name="excludeMethods">setUpForInsertOrUpdate</param>
            </interceptor-ref>
            <result name="success">/EmployeeRegistrationForm.jsp</result>                        
        </action>
        
        <action name="insertOrUpdate" method="insertOrUpdate" class="learnstruts.demo.action.EmployeeAction">
            <result name="input">/EmployeeRegistrationForm.jsp</result>
            <result name="success">/ListOfEmployee.jsp</result>
            <result name="getList" type="chain">listOfEmployee</result>
            <result name="failure">/error.jsp</result>
        </action>
       
        <action name="deleteEmployee" method="deleteEmployee" class="learnstruts.demo.action.EmployeeAction">
            <interceptor-ref name="validation">
                <param name="excludeMethods">deleteEmployee</param>
            </interceptor-ref>
            <result name="success">/ListOfEmployee.jsp</result>
            <result name="failure">/error.jsp</result>
        </action>
       
        <action name="listOfEmployee" method="listOfEmployees" class="learnstruts.demo.action.EmployeeAction">
            <interceptor-ref name="validation">
                <param name="excludeMethods">listOfEmployees</param> 
            </interceptor-ref>
            <result name="success">/ListOfEmployee.jsp</result>
        </action>

    </package> 

</struts>

EmployeeAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN" 
"http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd">


<validators>

    <field name="employee.firstName">

        <field-validator type="requiredstring" short-circuit="true">
            <message>FIRST NAME is required</message>
        </field-validator>

        <field-validator type="regex">
            <param name="expression"><![CDATA[^[a-zA-Z]+$]]>
            </param>
            <message>FIRST NAME is an invalid</message>
        </field-validator>

    </field>
    
    <field name="employee.lastName">

        <field-validator type="requiredstring" short-circuit="true">
            <message>LAST NAME is required</message>
        </field-validator>
	    
        <field-validator type="regex">
            <param name="expression"><![CDATA[^[a-zA-Z]+$]]>
            </param>
            <message>LAST NAME is an invalid</message>
        </field-validator>

    </field>

    <field name="employee.gender">

        <field-validator type="required" short-circuit="true">
            <message>Please select your GENDER</message>
        </field-validator>
	
	    
    </field>
    
    <field name="employee.birthDate">

        <field-validator type="required" short-circuit="true">
            <message>Please enter your BIRTH DATE</message>
        </field-validator>

        <field-validator type="regex">
            <param name="expression"><![CDATA[^[(?:0[1-9]|[12][0-9]|[3][01])\\/(?:0[1-9]|1[0-2])\\/(?:20\\d{2})]$]]>
            </param>
            <message>BIRTH DATE is an invalid. Please enter in dd/MM/yyyy format.</message>
        </field-validator>

    </field>
    
    <field name="employee.currentAddress">

        <field-validator type="requiredstring" short-circuit="true">
            <param name="trim">true</param>
            <message>Please enter your CURRENT ADDRESS</message>
        </field-validator>

        <field-validator type="stringlength">
            <param name="maxLength">10</param>
            <message>CURRENT ADDRESS should contain 200 characters only</message>
        </field-validator>

    </field>
    
    <field name="employee.permenentAddress">
    
        <field-validator type="stringlength">
            <param name="maxLength">200</param>
            <message>PERMENENT ADDRESS should contain 200 characters only</message>
        </field-validator>
    
    </field>

    <field name="employee.programmingLanguagesKnown">

  
        <field-validator type="required" short-circuit="true">
            <message>Please select PROGRAMMING LANGUAGES KNOWN</message>
        </field-validator>

    </field>  
    
    <field name="employee.degreeId">

        <field-validator type="required" short-circuit="true">
            <message>Please select HEIGHEST EDUCATIONAL QUALIFICATION</message>
        </field-validator>
	    

    </field>
    
    <field name="employee.emailAddress">

        <field-validator type="requiredstring">
            <message>EMAIL ADDRESS is required</message>
        </field-validator>

    </field>
   
    <field name="employee.mobileNo">

        <field-validator type="requiredstring" short-circuit="true">
            <message>MOBILE NO is required</message>
        </field-validator>
	   
        <field-validator type="regex">
            <param name="expression"><![CDATA[^[0-9]+$]]>
            </param>
            <message>MOBILE NO is an invalid</message>
        </field-validator>
	   
    </field>
   
    <field name="employee.landLineNo">

        <field-validator type="requiredstring" short-circuit="true">
            <message>LAND LINE NO is required</message>
        </field-validator>
	   
        <field-validator type="regex">
            <param name="expression"><![CDATA[^[0-9]+$]]>
            </param>
            <message>LAND LINE is an invalid</message>
        </field-validator>

    </field>
   
    <field name="employee.expectedSalary">

        <field-validator type="required" short-circuit="true">
            <message>EXPECTED SALARY is required</message>
        </field-validator>
	   
        <field-validator type="regex">
            <param name="expression"><![CDATA[^[0-9]+$]]>
            </param>
            <message>EXPECTED SALARY is an invalid</message>
        </field-validator>   
   
    </field>
   
    <field name="employee.city">
   
        <field-validator type="required">
            <message>Please select CITY</message>
        </field-validator>
   
    </field>
   
    <field name="employee.hobby">

        <field-validator type="required" short-circuit="true">
            <message>Please select atleast one HOBBY</message>
        </field-validator>


    </field>
      
</validators>

EmployeeAction.java

/**
 *
 */
package learnstruts.demo.action;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import learnstruts.demo.bean.Employee;
import learnstruts.demo.bean.HeighestEducationalQualification;
import learnstruts.demo.bean.Hobby;
import learnstruts.demo.bean.IncomeLevel;
import learnstruts.demo.bean.ProgrammingLanguagesKnown;
import learnstruts.demo.dao.EmployeeDBDAO;
import learnstruts.demo.service.CityDAOService;
import learnstruts.demo.service.CityService;
import learnstruts.demo.service.HeighestEducationalQualificationDAOService;
import learnstruts.demo.service.HeighestEducationalQualificationService;
import learnstruts.demo.service.HobbyDAOService;
import learnstruts.demo.service.HobbyService;
import learnstruts.demo.service.IncomeLevelService;
import learnstruts.demo.service.IncomeLevelServiceDAO;
import learnstruts.demo.service.ProgrammingLanguagesKnownService;
import learnstruts.demo.service.ProgrammingLanguagesKnownServiceDAO;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Taher Tinwala
 * @date Jan 7, 2010
 * @time 4:48:34 PM
 * @project struts2-application
 */
//@Validation
public class EmployeeAction extends ActionSupport {

    private static CityService cityService = new CityDAOService();
    private static HobbyService hobbyService = new HobbyDAOService();
    private static ProgrammingLanguagesKnownService programmingLanguagesKnownService = new ProgrammingLanguagesKnownServiceDAO();
    private static IncomeLevelService incomeLevelService = new IncomeLevelServiceDAO();
    private static HeighestEducationalQualificationService heighestEducationalQualificationService = new HeighestEducationalQualificationDAOService();
    private Employee employee;
    private List<Employee> employees;
    private List<IncomeLevel> incomeLevels;
    private List<HeighestEducationalQualification> heighestEducationalQualifications;
    private EmployeeDBDAO dao = new EmployeeDBDAO();
    private static Map<String, String> gujaratCities = new HashMap<String, String>();
    private static Map<String, String> maharashtraCities = new HashMap<String, String>();
    private static Map<String, String> madhyaPradeshCities = new HashMap<String, String>();
    private static Map<String, String> rajasthanCities = new HashMap<String, String>();
    private List<Hobby> hobbies;
    private List<ProgrammingLanguagesKnown> programmingLanguagesKnownList;
    private String actionType;
    private Integer employeeId;

    public Integer getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(Integer employeeId) {
        this.employeeId = employeeId;
    }

    public String setUpForInsertOrUpdate() throws SQLException, NullPointerException, Exception {
        System.out.println("setUpForInsertOrUpdate" + getEmployeeId());
        getFormData();
        if (employee == null) {
            employee = new Employee();
            System.out.println("ID = " + employee.getId());
        }
        if (employee != null && employee.getId() != null) {
            // Insert code for getting value for Employee via DB call for update
            employee = dao.getByPkEmployee(employee.getId());
        }
        return SUCCESS;
        //return INPUT;
    }

    public String insertOrUpdate() throws SQLException, Exception {
        String result = "input";
        System.out.println("insertOrUpdate" + employee.getId());
        if (employee == null || employee.getId() == null) {
            //Code for insert comes heres
            boolean insertResult = dao.addEmployee(employee);
            result = "success";
            if (insertResult) {
                result = listOfEmployees();
            } else {
                getFormData();
                addActionError("Insert Fails");
                result = "input"; // Goto error pager Insert Fails  
            }
            System.out.println("Insert Data");
        } else {
            boolean isUpdateSuccessfull = dao.updateEmployee(employee);
            if (isUpdateSuccessfull) {
                listOfEmployees();
                result = "getList";
            } else {
                result = "failure";
            }
            /*}else{
             // Code for delete comes here
             System.out.println("Inside Delete");
				
             boolean isDeleteSuccessfull  = dao.deleteEmployee(employee.getId());
             if(isDeleteSuccessfull){
             result = "getList";
					
             }else{
             result = "failure";
             }
             }*/
            /*System.out.println("Update Data");*/
        }

        return result;
    }

    public String listOfEmployees() throws SQLException, Exception {
        String result = "success";
        employees = dao.getAllEmployeeList();
        return result;
    }

    public String deleteEmployee() throws SQLException, Exception {
        String result = "success";
        boolean isDelete = dao.delete(employee.getId());
        if (isDelete) {
            listOfEmployees();
            result = "success";
        } else {
            result = "failure";
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    private void getFormData() throws NullPointerException, Exception {
        gujaratCities = cityService.getAllGujaratCityMap();
        madhyaPradeshCities = cityService.getAllMadhyaPradeshCityMap();
        maharashtraCities = cityService.getAllMaharashtraCityMap();
        rajasthanCities = cityService.getAllRajasthanCityMap();
        hobbies = hobbyService.getAllHobbiesList();
        programmingLanguagesKnownList = programmingLanguagesKnownService.getAllProgrammingLanguagesKnownList();
        incomeLevels = incomeLevelService.getAllIncemeLevelsList();
        heighestEducationalQualifications = heighestEducationalQualificationService.getAllHeighestEducationalQualificationsList();

        Map session = ActionContext.getContext().getSession();

        session.put("gujaratCities", gujaratCities);
        session.put("madhyaPradeshCities", madhyaPradeshCities);
        session.put("maharashtraCities", maharashtraCities);
        session.put("rajasthanCities", rajasthanCities);
        session.put("hobbies", hobbies);
        session.put("programmingLanguagesKnownList", programmingLanguagesKnownList);
        session.put("incomeLevels", incomeLevels);
        session.put("heighestEducationalQualifications", heighestEducationalQualifications);

    }

    //@RequiredStringValidator(message = "Enter FullName")
    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }

    public String getActionType() {
        return actionType;
    }

    public void setActionType(String actionType) {
        this.actionType = actionType;
    }
}

ListOfEmployee.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!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=ISO-8859-1">
        <title>List Of Employees</title>
        <script language="javascript">

            function updateStudent(eid){
                var f = document.listOfEmployees;
                f.employeeId.value = eid;
                alert(f.employeeId.value);
                f.action = "/struts-sample/setUpForInsertOrUpdate.action";
                f.submit();
            }


            function deleteStudent(eid){
                var f = document.listOfEmployees;
                var conf = window.confirm('Are you sure you want to delete ?');
                if(conf){
                    f.id.value = eid;
                    f.actionType.value = "delete";
                    f.action = "/struts-sample/deleteEmployee.action";
                    f.submit();
                }	
            }

        </script>
    </head>
    <body>
        <br><br><br><br>
        <s:form name="listOfEmployees"  method="post">
            <s:hidden name="employeeId" />
            <s:hidden name="employee.id"  value="159"/>
            <s:hidden name="actionType" />
            <table width="100%" height="100%" align="center" border="1"> 
                <tr>
                    <td>Name</td>
                    <td>Current Address</td>
                    <td>Gender</td>
                    <td>Email Address</td>
                    <td>Mobile No</td>
                    <td>LandLine No</td>
                    <td>EDIT | DELETE</td>
                </tr>
                <s:iterator value="employees" status="status">
                    <tr>
                        <td><s:property value="firstName" />&nbsp;<s:property value="lastName" /></td>
                        <td><s:property value="currentAddress" /></td>
                        <td><s:property value="gender" /></td>
                        <td><s:property value="emailAddress" /></td>
                        <td><s:property value="mobileNo" /></td>
                        <td><s:property value="landLineNo" /></td>
                        <td>

                            <%--        <s:url id="update" action="setUpForInsertOrUpdate">
                                               <s:param name="id" value="id"/>
                                                </s:url>
                                                <s:a href="%{update}">EDIT</s:a>
                            --%>		
                            <s:url id="update" action="setUpForInsertOrUpdate">
                                <s:param name="id" value="%{id}"/>
                            </s:url> 
                            <s:a href="%{update}">Edit</s:a>
                            <s:a href="#" onclick="java:updateStudent('%{id}')">EDIT</s:a>&nbsp; |
                            <s:a href="#" onclick="java:deleteStudent('%{id}')">DELETE</s:a>
                            </td>
                        </tr>
                </s:iterator>				 
            </table>
        </s:form>
    </body>
</html>
Advertisements
This entry was posted in Just 4 Knowledge, Struts 2.0 and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s