Pages Navigation Menu

Coding is much easier than you think

Difference between # , $ and % signs in Struts2

Posted by in Struts 2 Tutorial, Struts-2

 
Use of #
 
OGNL is used to refer to objects in the ActionContext as follows:

  • myObject: object in the ValueStack, such as an Action property
  • #myObject: object in the ActionContext but outside of the ValueStack…
    • #myObject: ActionContext object that has been created using the Struts2 data tags with the default action scope (e.g., <s:set name=”data” value=”Some data” />, referenced by<s:property value=”#data” />)
    • #parameters.myObject: request parameter
    • #request.myObject: request-scoped attribute
    • #session.myObject: session-scoped attribute
    • #application.myObject: application-scoped attribute
    • #attr.myObject: attribute in page, request, session, or application scope, searched in that order.

 
** UPDATE: Struts 2 Complete tutorial now available here.
 
The scoped map references above (parameters, request, session, and application) can be made one of two ways:

1. #scopeName['myObject']
2. #scopeName.myObject

 

Use of $
 

Struts2 OGNL does not make use of the dollar sign. However, it can be used to evaluate JSTL expressions. For example:
 

Struts2: <s:property value="someProperty" />
(is equivalent to)
JSTL: ${someProperty}

 

Use of %
 

% character is used to force OGNL evaluation of an attribute that would normally interpreted as a String literal. For eample,
 

<s:url id="urlAtt" action="urlTag.action">
<s:a href="%{urlAtt}">Call Action</s:a>

Now <s:a> tag will query the stack for urlAtt value.

 

Read More

Common Support class for Action classes in Struts 2

Posted by in Struts 2 Tutorial, Struts-2

 
When you are about to create a complex application in struts 2, it is better to create a Base action class for all your actions and make this class extend ActionSupport and implement all necessary interfaces such as SessionAware, ParameterAware, HttpServletRequest, HttpServletResponse etc and implement all other common logic for your actions in this class. So now when you are about to create an action class, just extending this support class will suit all your need in action class.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Following is a snippet of my ApplicationSupportAction class:
 

import java.util.Map;

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

import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;

public abstract class ApplicationSupportAction extends ActionSupport implements
		SessionAware, ServletRequestAware, ParameterAware, ServletResponseAware
{
	private static final long serialVersionUID = 1L;

	// Field to store session context.
	private Map<String, Object> session;

	// Field to store request parameters.
	private Map<String, String[]> parameters;

	// Field to store HttpServletRequest.
	private HttpServletRequest servletRequest = null;

	// Field to store HttpServletResponse.
	private HttpServletResponse servletResponse = null;

	// Result code for session expired action.
	public final static String SESSION_EXPIRED = "SessionExpired";

	// Result code for Logout action.
	public final static String LOGOUT = "logout";

	// .....

	// action to be triggered when session expires
	public String execute() throws Exception
	{
		HttpSession sessionObj = servletRequest.getSession(true);

		if (sessionObj.getAttribute("currentUser") == null)
		{
			return SESSION_EXPIRED;
		}
		return executeAction();
	}

	public abstract String executeAction() throws Exception;

	@Override
	public void setSession(Map<String, Object> session)
	{
		this.session = session;
	}

	@Override
	public void setParameters(Map<String, String[]> parameters)
	{
		this.parameters = parameters;
	}

	@Override
	public void setServletResponse(HttpServletResponse servletResponse)
	{
		this.servletResponse = servletResponse;
	}

	@Override
	public void setServletRequest(HttpServletRequest servletRequest)
	{
		this.servletRequest = servletRequest;
	}

	public Map<String, Object> getSession()
	{
		return session;
	}

	public Map<String, String[]> getParameters()
	{
		return parameters;
	}

	public HttpServletRequest getServletRequest()
	{
		return servletRequest;
	}

	public HttpServletResponse getServletResponse()
	{
		return servletResponse;
	}
	
	public String getCurrentUser()
	{
		return (String) session.get("currentUser");
	}

	public void setCurrentUser(String currentUser)
	{
		session.put("currentUser", currentUser);
	}
}

 

You can handle following common concerns in the ApplicationSupportAction class:
1. Session
2. Parameters
3. Http Request and response
4. Validating session.
5. Common result codes etc.
 
ApplicationSupportAction class would reduce your action class code to a large extent by handling lot of common concerns in one centralized place.

 

Read More

Best way to check a string against null in java?

Posted by in Java

 
String in Java is considered empty if its not null and it’s length is 0. But before checking length you should verify that String is not null because calling length() on null String will result in NullPointerException.
 
Apache commons lang has a StringUtils class which has static method isEmpty(String input), which returns true if input string is null or has length equal to zero.
 
Output of StringUtils for various input :

StringUtils.isEmpty("value")   = false
StringUtils.isEmpty(" ")       = false
StringUtils.isEmpty("")        = true
StringUtils.isEmpty(null)      = true

 

Read More

Struts 2 iterator tag example

Posted by in Struts 2 Tutorial, Struts-2 | 3 comments

 

dwd2
Zip file –IteratorTag.zip
War file –IteratorTag.war

 
Struts 2 Iterator will iterate over a value. An iterable value can be any of: java.util.Iterator,java.util.Collection.
In this tutorials, we will create a list and use Iterator tag to loop over it and get the iterator status with IteratorStatus.
 
Using IteratorStatus object one can get information about the status of the iteration, such as:

index: current iteration index, starts on 0 and increments in one on every iteration
count: iterations so far, starts on 1. count is always index + 1
first: true if index == 0
last: true if current iteration is the last iteration
even: true if (index + 1) % 2 == 0
odd: true if (index + 1) % 2 == 1
 
** UPDATE: Struts 2 Complete tutorial now available here.
 

Jsp -Iterator example
 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@taglib prefix="s" uri="/struts-tags"%>

<title>Students Details</title>
<style type="text/css">
.odd
{
background-color: silver;
}
.even
{
background-color: white;
}
</style>
<html>
<body>
<h4>Simple Iterator</h4>
<table>
<tr>
    <td width="20%">RollNo</td>
    <td width="20%" >Student Name</td>
    <td width="20%">Department</td>
    <td width="20%">Percentage</td>
</tr>

<s:iterator value="students">
<tr>
    <td width="20%"><s:property value="rollNo" /></td>
    <td width="20%" ><s:property value="studentName"/></td>
    <td width="20%"><s:property value="department"/></td>
    <td width="20%"><s:property value="percentage"/></td>
</tr>
</s:iterator>
</table>
<br/>

<h4>Iterator with Iterator Status</h4>
<table>
<tr>
    <td width="10%">So No</td>
    <td width="20%">RollNo</td>
    <td width="20%" >Student Name</td>
    <td width="20%">Department</td>
    <td width="20%">Percentage</td>
</tr>

<s:iterator value="students" status="rowstatus">
<tr class="<s:if test="#rowstatus.odd == true ">odd</s:if><s:else>even</s:else>">
    <td><s:property value="#rowstatus.count"/></td>
    <td width="20%"><s:property value="rollNo" /></td>
    <td width="20%" ><s:property value="studentName"/></td>
    <td width="20%"><s:property value="department"/></td>
    <td width="20%"><s:property value="percentage"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>

 
Action Class
 

package com.simplecode.action;

import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.simplecode.form.StudentBean;

public class StudentAction extends ActionSupport
{
private static final long serialVersionUID = 1L;
private List<StudentBean> students = new ArrayList<StudentBean>();

public String fetchStudentList()
{
students.add(new StudentBean("o7ba062", "Lavanya", "IT", 70));
students.add(new StudentBean("o7bb040", "Jaya Prakash", "ECE", 86));
students.add(new StudentBean("o7bd047", "Sundar", "MECH", 85));
students.add(new StudentBean("o7bb039", "Ibrahim Sha", "ECE", 85));
students.add(new StudentBean("o7bb009", "Aswin", "ECE", 84));
students.add(new StudentBean("o7ba027", "Nilafar", "IT", 82));
students.add(new StudentBean("o7bc079", "Nisha", "CSC", 81));
	
return SUCCESS;
}

public List<StudentBean> getStudents()
{
	return students;
}

public void setStudents(List<StudentBean> students)
{
	this.students = students;
}

}

 
Demo
 
Iterator Struts2
 

Read More

Struts 2 If, Else, ElseIf Conditional/Control tag example

Posted by in Struts 2 Tutorial, Struts-2

 
Struts 2 If, ElseIf and Else tags are used to perform basic condition checking.

These are the following scenario in real world application to check the condition.

1. Condition checking using Boolean variable.
2. Condition checking using String object.
3. Condition checking using collection object / bean object
4. Condition checking using integer data type

 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Now see the example on these scenario one by one.
 
1. Condition checking using Boolean variable.

<s:if test="booleanValue">
   returning TRUE.
</s:if>
<s:else>
   returning FALSE.
</s:else>

 
2. Condition checking using String object.

<s:if test="%{stringValue==null}">
   string is null
</s:if>
<s:else>
   string is not null
</s:else>

 
3. Condition checking using collection object / bean object

<s:if test="%{arrayList.size()==0}">
   object size is zero
</s:if>
<s:else>
   object size is greater than zero
</s:else>

 
4. Condition checking using integer data type

<s:if test="%{integerValue==0}">
   integer is zero
</s:if>
<s:elseif test="%{integerValue > 0}">
   integer is greater than zero
</s:elseif>
<s:else>
   integer is lesser than zero
</s:else>

 
Jsp Page
 
On embedding all the above scenario in a complete Jsp page

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>ControlTag - If Else Condition</title>
</head>
<body>
<h4>Control Tag</h4>

// For Boolean Value
<s:if test="booleanValue">
   returning TRUE.
</s:if>
<s:else>
   returning FALSE.
</s:else>

// For String Value
<s:if test="%{stringValue==null}">
   string is null
</s:if>
<s:else>
   string is not null
</s:else>

// For Integer Value
<s:if test="%{integerValue==0}">
   integer is Zero
</s:if>
<s:elseif test="%{integerValue > 0}">
   integer is greater than zero
</s:elseif>
<s:else>
   integer is lesser than zero
</s:else>

// For Object Value
<s:if test="%{arrayList.size()==0}">
   object size is zero
</s:if>
<s:else>
   object size is greater than zero
</s:else>

</body>
</html>

 

Acion Class
 

package com.simplecode.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.Action;

public class ControlTag implements Action
{
	private List<String> arrayList = new ArrayList<String>();
	private String stringValue;
	private boolean booleanValue;
	private int integerValue;

	public String execute()
	{
		arrayList.add("Simple");
		arrayList.add("Code");
		arrayList.add("Stuffs");
		
		integerValue = -2;
		booleanValue = true;
		stringValue = "someValues";
		return SUCCESS;
	}

	public List<String> getArrayList()
	{
		return arrayList;
	}

	public void setArrayList(List<String> arrayList)
	{
		this.arrayList = arrayList;
	}

	public String getStringValue()
	{
		return stringValue;
	}

	public void setStringValue(String stringValue)
	{
		this.stringValue = stringValue;
	}

	public boolean isBooleanValue()
	{
		return booleanValue;
	}

	public void setBooleanValue(boolean booleanValue)
	{
		this.booleanValue = booleanValue;
	}

	public int getIntegerValue()
	{
		return integerValue;
	}

	public void setIntegerValue(int integerValue)
	{
		this.integerValue = integerValue;
	}
}

 
Demo
 
On runnig the application
 
ControlTag
 

Read More
Page 10 of 41«First...89101112...203040...Last»