Saturday, December 17, 2016

Struts 1 Login Examples step by step using eclipse.

1. Download jars required for Login example using struts-1 framework.

  • javax.servlet.jar (http://www.java2s.com/Code/Jar/j/Downloadjavaxservletjar.htm)
  • struts-1.3.10-lib.zip (http://struts.apache.org/download.cgi)
  • struts-taglib-1.3.5.jar (http://www.java2s.com/Code/Jar/s/Downloadstrutstaglib135jar.htm)

2. Create a dynamic web project (named as 'LoginExample') in eclipse.














3. Extract all downloaded jars (as mentioned in point number 1) and then go to eclipse and click on your project 'LoginExample' and and you will a 'lib' folder under "WebContent/WEB-INF".directory. Then copy paste all jar files under this "lib" folder.

5.  Create folder structures for this project as below,

  • Create two packages ("com.struts1.actions" and "com.struts1.forms") under "src" folder.
  • Create one folder (Presentations) under "WebContent"

















6. Open deployment descriptor (web.xml) file and remove all code available in this file and copy-paste the below written code for this project.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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>StrutsApplication</display-name>
<welcome-file-list>
<welcome-file>Presentations/Login.jsp</welcome-file>
</welcome-file-list>
<servlet>
   <servlet-name>Struts</servlet-name>
   <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
   <init-param>
     <param-name>config</param-name>
     <param-value>/WEB-INF/struts-config.xml</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
   <servlet-name>Struts</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

7. Create an XML file named as "struts-config.xml" under "WEB-INF" folder (same location where web.xml present) and then delete the source code available here and copy paste the below code.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
         "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
         "http://struts.apache.org/dtds/struts-config_1_3.dtd">
         
<struts-config>
   <!-- ========== Form Bean Definitions ================================== -->
   <form-beans>
       <form-bean name="loginForm" type="com.struts1.forms.LoginForm"/>
   </form-beans>
   <!-- ========== Action Mapping Definitions ============================= -->
   <action-mappings>
           <action name="loginForm" path="/Login" type="com.struts1.actions.LoginAction" scope="request" input="/Login.jsp">
               <forward name="failure" path="Presentations/Failure.jsp" redirect="true"/>
               <forward name="success" path="Presentations/Success.jsp" redirect="true"/>
           </action>
   </action-mappings>
</struts-config>

8. Now create 3 JSP files under your created folder named as "Presentations". The files are as follows;
  • Login.jsp
  • Success.jsp
  • Failure.jsp


Copy paste the below source code for the above 3 JSP files,

================= Login.jsp =================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
 <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<!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>Insert title here</title>
</head>
<body>
<html:form action="/Login" method="post">
User Name:<html:text property="userName"/></br>
Password:<html:password property="password"/></br>
<html:submit/>
</html:form>
</body>
</html>
================= Success.jsp =================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
SUCCESS
</body>
</html>
================= Failure.jsp =================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
FAILURE
</body>
</html>

9. Now create a POJO class named as "LoginForm.java" under "com.struts1.forms" package and the file contain is as follows,

package com.struts1.forms;

import org.apache.struts.action.ActionForm;

public class LoginForm extends ActionForm {
private String userName;
private String password;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}

10. Now create an Action class named as "LoginAction.java" under "com.struts1.actions" package and the file contain is as follows,

package com.struts1.actions;

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.struts1.forms.LoginForm;

public class LoginAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest req, HttpServletResponse response)
throws Exception {
LoginForm frm = (LoginForm) form;
if (frm.getUserName().equalsIgnoreCase("admin")
&& frm.getPassword().equalsIgnoreCase("admin")) {
return mapping.findForward("success");
} else {
return mapping.findForward("failure");
}
}
}






11. Now configure server to run your web project. For this example I have used "Apache Tomcat 6" and run the project and it will open the "Login" page.



















Login is page is as follows. You can use any browser to run this project using the below URL.









12. For this example we set user name and password as "admin" and "admin" respectively.
 So once click on submit button with correct user name and password, it will redirect to "Success.jsp" page and for invalid credential it will redirect to "Failure.jsp" page.

With valid credential ==>







With Invalid credential ==>








================= Total description =================

Will be updated soon.

Thursday, May 19, 2016

Excel data fetching using java.

Scenario: In a medical shop software, there is a requirement to fetch medicine name and medicine type from a excel and the validation scenario is as follows, 
  1. Excel should be [.xls] extension.
  2. Fetch data from sheet one only.
  3. Excel should have two columns and multiple rows.
  4. Column headers should be "Name" and "Type" respectively.
  5. No blank column or row is supported.
  6. Only unique value will be fetched.
Excel data:
Name
Type
Calpol
TAB
Dortin
TAB
Dortin
INJ
Netorgain
PWDR
Voloni
GEL
Calpol
TAB
Dortin
TAB
Dortin
INJ
Netorgain
PWDR
Voloni
GEL

Expected OUTPUT :
Netorgain,PWDR
Voloni,GEL
Calpol,TAB
Dortin,TAB
Dortin,INJ

#################################################
External library required:jxl.jar
#################################################
package com.test.upload;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

enum MEDCINE_TYPE {
TAB, CAP, INJ, GEL, PWDR, OTHER
};

public class ExcelDataFetch {
final static String HEADER1 = "Name";
final static String HEADER2 = "Type";

public static void main(String[] args) {
String filePath = "D://test.xls";
FileInputStream fIStream = getFileInputStream(filePath);
if (fIStream != null) {
Workbook wb;
try {
wb = Workbook.getWorkbook(fIStream);
// Accessing to Sheet1.
Sheet sh = wb.getSheet(0);
// Fetching header from excel.

if (isCorrectHeaderFormat(sh)) {
List<String> lstOfXlData = getListExcelData(sh);
if (lstOfXlData != null && lstOfXlData.size() > 0) {
if (isValidMedTypeProvided(lstOfXlData)) {
Set<String> vaildUniqueData = getValidUniqueData(lstOfXlData);
if (vaildUniqueData != null) {
Iterator<String> it = vaildUniqueData
.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
} else {
System.out
.println("Please provides vaild med type. [TAB, CAP, INJ, GEL, PWDR, OTHER]");
}
}

} else {
System.out
.println("File header is not correct. Please set correct row headers "
+ "[Row one and column one as 'Name' and Row one and column 2 as 'Type'].");
}

} catch (BiffException e) {
System.out
.println(e.getMessage()
+ " [Please select file format Excel 97-2003 (ext. is .xls)]");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

private static boolean isValidMedTypeProvided(List<String> lstOfXlData) {
Iterator<String> it = lstOfXlData.iterator();
String strOfEnum = "";
for (MEDCINE_TYPE mt : MEDCINE_TYPE.values())
strOfEnum = strOfEnum + String.valueOf(mt.name());
while (it.hasNext()) {
String lstVal = it.next();
if (lstVal != null && lstVal.length() > 0) {
String type = lstVal.substring(lstVal.indexOf(',') + 1,
lstVal.length());
if (!strOfEnum.contains(type))
return false;
}

}
return true;
}

private static boolean isCorrectHeaderFormat(Sheet sh) {
Cell Col0Row0 = sh.getCell(0, 0);
Cell Col1Row0 = sh.getCell(1, 0);
if (Col0Row0 != null && Col1Row0 != null
&& Col0Row0.getContents().equalsIgnoreCase(HEADER1)
&& Col1Row0.getContents().equalsIgnoreCase(HEADER2)) {
return true;
}
return false;
}

private static Set<String> getValidUniqueData(List l) {
Set<String> s = new HashSet<String>();
if (l != null && l.size() > 0) {
s.addAll(l);
}
return s;
}

private static List<String> getListExcelData(Sheet sh) {
int lengthOfValidRows = getlengthOfValidRows(sh);
int i = 1;
List<String> lst = new ArrayList<String>();
Set<String> s = new HashSet<String>();
while (i < lengthOfValidRows + 1) {
if (sh.getCell(0, i) != null && sh.getCell(1, i) != null)
lst.add(sh.getCell(0, i).getContents() + ","
+ sh.getCell(1, i).getContents());
i++;
}
return lst;
}

private static int getlengthOfValidRows(Sheet sh) {
int rowLen = 0, i = 1;
while (i != 0) {
try {
sh.getCell(0, i);
rowLen = i;
i++;
} catch (ArrayIndexOutOfBoundsException ex) {
return rowLen;
}
}
return rowLen;
}

private static FileInputStream getFileInputStream(String fileNameEithPath) {
FileInputStream fis = null;
try {
System.out.println("Checking file availability ...........");
fis = new FileInputStream(fileNameEithPath);
System.out.println("File exists ...........");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
return fis;
}

}

Monday, April 13, 2015

Template Pattern

package com.exmpl.templatePattern;
//This is a POJO class for employee.
public class Employee {
       private String userName;
       private String password;
       private String empName;
       private int empId;
       private String empRole;

       public String getUserName() {
              return userName;
       }

       public void setUserName(String userName) {
              this.userName = userName;
       }

       public String getPassword() {
              return password;
       }

       public void setPassword(String password) {
              this.password = password;
       }

       public String getEmpName() {
              return empName;
       }

       public void setEmpName(String empName) {
              this.empName = empName;
       }

       public int getEmpId() {
              return empId;
       }

       public void setEmpId(int empId) {
              this.empId = empId;
       }

       public String getEmpRole() {
              return empRole;
       }

       public void setEmpRole(String empRole) {
              this.empRole = empRole;
       }

       @Override
       public String toString() {
              return "Employee [userName=" + userName + ", password=" + password
                           + ", empName=" + empName + ", empId=" + empId + ", empRole="
                           + empRole + "]";
       }
}

-------------------------------------------------------------------- 
// This class is responsible for creating a template. 
package com.exmpl.templatePattern;

public abstract class TemplateClass {
       public boolean isAuth = false;

       // Template method
       public void displayEmployeeDetails() {
              initializeEmployeeDetails();
              authenticateEmployee();
              if(isAuth == true)
                     performOperation();
       }

       public abstract void initializeEmployeeDetails();

       public abstract void performOperation();

       public abstract void authenticateEmployee();
}

--------------------------------------------------------------------------
// This class extends template class and define it's abstract method. 
package com.exmpl.templatePattern;

public class EmployeeOne extends TemplateClass {
       Employee emp = new Employee();

       @Override
       public void initializeEmployeeDetails() {
              emp.setUserName("admin");
              emp.setPassword("admin");
              emp.setEmpName("Mr. Stive");
              emp.setEmpId(0001);
              emp.setEmpRole("Developer");
       }

       @Override
       public void authenticateEmployee() {
              if (emp.getUserName().equalsIgnoreCase("admin")
                           && emp.getPassword().equalsIgnoreCase("admin")) {
                     isAuth = true;
              }else{
                     System.out.println("Invalid user name and/or password");
              }
       }

       @Override
       public void performOperation() {
              System.out.println("Employee details is as follows: "+emp);
       }
}

----------------------------------------------------------------------------------------------------------
// This class extends template class and define it's abstract method.  
package com.exmpl.templatePattern;

public class EmployeeTwo  extends TemplateClass {
       Employee emp = new Employee();

       @Override
       public void initializeEmployeeDetails() {
              emp.setUserName("adminadmin");
              emp.setPassword("adminadmin");
              emp.setEmpName("Mr. Mark");
              emp.setEmpId(0001);
              emp.setEmpRole("Manager");
       }

       @Override
       public void authenticateEmployee() {
              if (emp.getUserName().equalsIgnoreCase("admin")
                           && emp.getPassword().equalsIgnoreCase("admin")) {
                     isAuth = true;
              }else{
                     System.out.println("Invalid user name and/or password");
              }
       }

       @Override
       public void performOperation() {
              System.out.println("Employee details is as follows: "+emp);
       }
}

-------------------------------------------------------------------------------
// From this class we are calling template method with different instance. 
package com.exmpl.templatePattern;

public class ClientClass {
       public static void main(String[] args) {
              TemplateClass empOne = new EmployeeOne();
              System.out.println("Details of Employe one: ");
              empOne.displayEmployeeDetails();

              TemplateClass empTwo = new EmployeeTwo();
              System.out.println("Details of Employe two: ");
              empTwo.displayEmployeeDetails();
       }

}
---------------------------------------------------------------------------------
Output ==>
Details of Employe one: 
Employee details is as follows: Employee [userName=admin, password=admin, empName=Mr. Stive, empId=1, empRole=Developer]
Details of Employe two: 
Invalid user name and/or password