Thursday, July 31, 2014

struts example






Struts example

Below post shows how to build simple application with struts.

open eclipse -> project -> create dynamic Webproject->

provide name as - struts_sample [As you like]

select Dynamic web module version as 2.5

Then click on Finish button.

-> open the web.xml , which available inside WEB-INF folder

copy the below code and paste in side web.xml .
      
             action 
              org.apache.struts.action.ActionServlet     
               
                   config                   /WEB-INF/struts-config.xml              
              1
  
     
		       action   
		       *.do
    


-> Create xml and name it as struts-config.xml inside WEB-INF.
->open the struts-config.xml and paste the below code inside the struts-config.xml

	  
  


		 
		
			 
		
											
		 
		 
			
				
				
			
			
				
				
			
		
	
	


-> Now it's time to start our work like creating jsp files, form classes, action classes and need to add required jars.

-> first we will write jsp page. Here i am writting 4 jsp pages
1. login.jsp
2. welcome.jsp
3. adduser.jsp
4. success.jsp

-> create one folder inside WebContent with name jsp [WebContent/jsp/login.jsp] -- this is for login details which will have user name and password along with validation.
paste the below code inside login.jsp

	<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%><%@taglib
	uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>



Login page



Login


-> create welcome.jsp [WebContent/jsp/welcome.jsp] -- this is for after successful login details .
paste the below code inside welcome.jsp
	
	<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>



Welcome page


	<%        String message = (String)request.getAttribute("message");    %>
	

Welcome User : <%= message %>

You have successfully logged in.

-> create adduser.jsp [WebContent/jsp/adduser.jsp] -- this contains user details along with required validation.
paste the below code inside adduser.jsp

	<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%><%@taglib
	uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>



Add User























-> create success.jsp [WebContent/jsp/success.jsp] -- this page will display after successful user details.
paste the below code inside success.jsp
	<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%><%@taglib
	uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>



Login page


	

success

successfully Added.
-> We need to create java classes.
-> create a package -> com.siva.form
-> com.siva.action

->create LoginForm.java inside com.siva.form package and paste the below code.
package com.siva.form;

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;

/**
 * 
 * @author sivaraju
 *
 */
public class LoginForm extends ActionForm {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1743531020254647308L;
	private String userName;
	private String password;

	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors actionErrors = new ActionErrors();
		if (userName == null || userName.trim().equals("")) {
			actionErrors.add("userName", new ActionMessage("error.username"));
		}
		try {
			if (password == null || password.trim().equals("")) {
				actionErrors.add("password",
						new ActionMessage("error.password"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return actionErrors;
	}

	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;
	}
}
->create UserForm.java inside com.siva.form and paste below code

  package com.siva.form;

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;

/**
 * 
 * @author sivaraju
 *
 */
public class UserForm extends ActionForm {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2087861874662967982L;
	private String userName;
	private String sex;
	private int age;

	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors actionErrors = new ActionErrors();
		try {
				if (userName == null || userName.trim().equals("")) {
					actionErrors.add("userName", new ActionMessage("error.username"));
				}
				if (sex == null || sex.trim().equals("")) {
					actionErrors.add("sex",new ActionMessage("error.sex"));
				}
				if (age <=0 ) {
					actionErrors.add("age",new ActionMessage("error.age"));
				}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return actionErrors;
	}

	public String getUserName() {
		return userName;
	}

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

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	
}
-> create LoginAction.java inside com.siva.action pakage and paste the below code
  package com.siva.action;

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.siva.form.LoginForm;

public class LoginAction extends Action {
	private static final String FAILURE = "failure";
	private static final String SUCCESS = "success";

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String target = null;
		LoginForm loginForm = (LoginForm) form;
		if (loginForm.getUserName().equals("admin")
				&& loginForm.getPassword().equals("admin123")) {
			target = SUCCESS;
			request.setAttribute("message", loginForm.getUserName());
		} else {
			target = FAILURE;
		}
		return mapping.findForward(target);
	}
}
-> create AddUserAction.java inside com.siva.action package and paste below code.
package com.siva.action;

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.siva.form.UserForm;
/**
 * 
 * @author sivaraju
 *
 */
public class AddUserAction extends Action {
	private static final String SUCCESS = "success";

	/**
	 * 
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm = (UserForm) form;
		System.out.println("username["+userForm.getUserName()+"]");
		System.out.println("Age["+userForm.getAge()+"]");
		System.out.println("Sex["+userForm.getSex()+"]");
		//If this details need to store in db. Then need to get the db details from data source object. Store as per requirement.
		return mapping.findForward(SUCCESS);
	}
	
	
}
->create MessageResource.properties file inside src/resource [src/resource/MessageResource.properties] and paste the below code
label.username = User Name
label.password = Password
label.welcome = Welcome 
error.username =Username is required.
error.password = Password is required.


label.age = Age
label.sex = Sex

label.adduser = Add User


error.age = Age is required field
error.sex=Sex is required field 
-> Add the below jars inside lib folder.(Among below jar's few of the jar's may not be required]
    bcprov-jdk14-121.jar
    commons-digester-2.1.jar
    commons-fileupload-1.1.1.jar
    commons-io-1.2.jar
    commons-lang-2.4.jar
    org-apache-commons-logging.jar
    org.apache.commons.beanutils.jar
    servlet-api.jar
    struts.jar
	
	
-> Right click on the project-> Run As-> Run On Server-> [select the server which ever server you want to run the application]. Tomcat is prefered. -> http://localhost:8080/struts_sample/login.jsp [ after submitting it will redirect to welcome.jsp]- username - admin / password - admin123 -> http://localhost:8080/struts_sample/jsp/adduser.jsp [after submitting it will redirec tto success.jsp]. In this way stuts application will work.

AddToAny

Contact Form

Name

Email *

Message *