Pages Navigation Menu

Coding is much easier than you think

Struts 2 tag not working in Display tag – Solution

Posted by in Display Tag, Struts 2 Tutorial, Struts-2 | 1 comment

 
Consider a scenario, such that you want to display a value of a column based on certain condition.
 
For example:
 
if a student’s marks is greater than 50 display as ‘pass’, if its less than 50 then display as ‘fail’. For this scenario, in a display tag, most of us result in the following code snippet.
 


<display:table name="ranklist" id="row" pagesize="10"  requestURI="rankAction" >

<s:if test="%{mark > 50}">
<display:column title="Status">Pass</display:column>
</s:if>
<s:elseif test="%{mark < 50}">
<display:column title="Status">Fail</display:column>
</s:elseif>

</display:table>

 
But here unfortunately this code does not works, because the variable “mark”is not reachable inside the display tag, since it is not associated with current display table.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Solution :
 
So the correct way of coding is:
 

<display:table name="ranklist" id="row" pagesize="10"  requestURI="rankAction" >

<display:column property="userName" title="User Name" />

<s:if test="%{#attr.row.mark > 50}">
<display:column title="Status">Pass</display:column>
</s:if>

<s:elseif test="%{#attr.row.mark < 50}">
<display:column title="Status">Fail</display:column>
</s:elseif>

</display:table>

 
Generalized way to access the struts 2 tag via display tag is :- #attr.tableIdName.tableField. So the only way to access a struts 2 tag inside displaytag, is to follow the above syntax.
 
Example : To access a property tag inside display tag :

<s:property name="userId" value="#attr.row.userId" />

 
Related Questions:

How to get checkbox values from displaytag using struts2
Displaytag export option is not working?
 

Read More

Concept of Servlets Vs Concept of Struts 2

Posted by in Java, Servlet, Struts 2 Tutorial, Struts-2 | 4 comments

 
In our previous article we have created a hello world program in struts2, in which I have passed parameter from request and setted in action class via a member variable, which may led you in some confusion, since in case of servlets the member variable in it are shared between all request and only those variable inside doget and dopost methods remains unique. So inorder to know why a member variable in struts 2 remains unique per request, we have look into the conceptual difference between Servlets and Struts 2. This article deals with the same.
 
Servlet vs Struts 2
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
In case of Servlet when we have N number of request then only one object is created out of which N number of Threads are created , in which a request object is created. So the objects inside the thread are safe and not shared with other thread objects.
 
But suppose if the Servlet has Member variable, then those variable are not thread safe, as they are shared between all the threads created for each request.

The above concept is depicted pictographically below.
 
Servlets-Struts-1-Concepts
 

Recommended Article

 

Note: Servlet & Struts 1 follows same concept.

 

In case of struts 2 for N number of request N number of object is created. So in this case, even the member variable for these objects are not shared between objects of other request, that the reason Struts 2 is said to be thread safe.
 

The concept of Struts 2 is depicted pictographically as below.
 
Struts-2-Concepts
 
In our next article we shall learn about the roles of Action class in struts 2.
 

Read More

Ajax implementation in Struts 2 without jQuery plugin

Posted by in Ajax, Struts-2 | 2 comments

Ajax in Servlet without jQuery
 
AJAX is a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can transfer data with a web server, without reloading the page.
 
This post elaborates on how to implement Ajax in Struts 2 application.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 

Action class

 

package com.simplecode.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.Action;

public class AjaxAction implements Action
{

   private String userName;
   private InputStream inputStream;
	
   public String ajaxMethod()
   {
	System.out.println("ajaxMethod() is called");
	byte[] bArray;
		
	if(!userName.isEmpty())
	{
	bArray = ("Welcome " + userName).getBytes();
	inputStream = new ByteArrayInputStream(bArray);
	}
	else
	{
	bArray = ("User name cant be blank").getBytes();
	inputStream = new ByteArrayInputStream(bArray);
	}
	
	return SUCCESS;
  }

  public String execute()
  {
	return SUCCESS;
  }
	
  public String getUserName()
  {
	return userName;
  }

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

  public InputStream getInputStream()
  {
	return inputStream;
  }
}

 

Recommended reading:

 

Jsp Pages

 

<%@taglib prefix="s" uri="/struts-tags"%>

<html>
<head>
<title>Ajax implementation in Struts 2 </title>

<script type="text/javascript">

//Get XMLHTTP Object
function getXMLHTTPObject()
{
var xmlhttpObject = null;
try
{
 // For Old Microsoft Browsers
 xmlhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
	try
	{
        // For Microsoft IE 6.0+
	xmlhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch (e1)
	{
        // No Browser accepts the XMLHTTP Object then false
	xmlhttpObject = false;
	}
}

if (!xmlhttpObject && typeof XMLHttpRequest != 'undefined')
{
        //For Mozilla, Opera Browsers
	xmlhttpObject = new XMLHttpRequest();
}
        // Mandatory Statement returning the ajax object created
	return xmlhttpObject;
}

	
// Change the value of the outputText field
function setAjaxOutput()
{
document.getElementById('userNameDiv').innerHTML = xmlhttpObject.responseText;
}

function handleServerResponse()
{
	if (xmlhttpObject.readyState == 4)
	{
		if (xmlhttpObject.status == 200)
		{
		setAjaxOutput();
		}
		else
		{
		    alert("Error during AJAX call. Please try again");
		}
	}
}
	
// Implement business logic
function doAjaxCall()
{
   xmlhttpObject = getXMLHTTPObject();
   if (xmlhttpObject != null)
   {
   var URL = "myAjaxAction.action?userName=" + document.getElementById('userName').value;
   xmlhttpObject.open("POST", URL, true);
   xmlhttpObject.onreadystatechange = handleServerResponse;
   xmlhttpObject.send(null);
   }
}
</script>
</head>

<body>
<h3>Ajax implementation in Struts2</h3>
<br/>
<div id="userNameDiv" style="color: red; font-weight: bold"></div>
<br/>
Please Enter your Name :
<s:textfield id="userName" theme="simple" name="userName" onblur="doAjaxCall();"/>
<br />
	
</body>
</html>

 

Also read:

 

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" namespace="/">
<action name="ajaxExample" class="com.simplecode.action.AjaxAction">
  <result>/ajax.jsp</result>
</action>
<action name="myAjaxAction" class="com.simplecode.action.AjaxAction" method="ajaxMethod">
  <result type="stream">
     <param name="contentType">text/html</param>
     <param name="inputName">inputStream</param>
  </result>
</action>
</package>
</struts>

 

Demo

 
On running the application
 
ajax in struts 2
 
Now giving the input as Jamil, the following output is obtained
 
ajax in struts 2 output
 
Here the struts 2 action is called onBlur() event automatically , and hence the above response is obtained in the webpage without refreshing the page.
 
download

Read More

How to Call Struts2 action from java script

Posted by in Struts-2

 

Action Class

 

package com.simplecode.action;
import com.opensymphony.xwork2.ActionSupport;

public class MyAction extends ActionSupport
{
	public String trueCall()
	{
		return SUCCESS;
	}

	public String falseCall()
	{
		return SUCCESS;
	}
}

 
** UPDATE: Struts 2 Complete tutorial now available here.
 

Jsp Pages

 
File : confirmBox.jsp
 

<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Calling Action from java script</title>
<script type="text/javascript">
function confirmBox()
{
var location = confirm("Do you want to go to this page?");
 if (location == true)
 	{
	window.location = "${pageContext.request.contextPath}/trueAction";
	}
        else
	{
	window.location = "${pageContext.request.contextPath}/falseAction";
	}
 }
</script>
</head>

<body>
	<s:submit value="Submit" onclick="confirmBox();" align="left"></s:submit>
</body>
</html>

 
Do read :

 
File : truePage.jsp
 

<html>
<head>
<title>Calling Action from java script</title>
</head>
<body>
	<h2>True Action</h2>
</body>
</html>

 
File :falsePage.jsp
 

<html>
<head>
<title>Calling Action from java script</title>
</head>
<body>
	<h2>False Action</h2>
</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" namespace="/">
<action name="trueAction" method="trueCall" class="com.simplecode.action.MyAction">
  <result>/truePage.jsp</result>
</action>

<action name="falseAction" method="falseCall" class="com.simplecode.action.MyAction">
  <result>/falsePage.jsp</result>
</action>
</package>
</struts>

 
Recommended Article :

 

Demo

 
On running the application we get
 
javascript in struts 2
 

Here on clicking the submit button, we get a confirm box, in which on clicking “Ok”, trueAction get’s called and on clicking “Cancel”, falseAction gets called.

Read More

Dynamically add, remove list of objects from jsp Using Struts2

Posted by in Struts-2 | 28 comments

 
In this article we shall learn on how to dynamically add, remove list of objects from jsp Using Struts2.
 
File : User.java (Model Class)
 

package com.simplecode.action;

import java.util.Collection;

public class User
{
	int regNo;
	String name;
	Collection<Address> addresses;

	public Collection<Address> getAddresses()
	{
		return addresses;
	}

	public void setAddresses(Collection<Address> addresses)
	{
		this.addresses = addresses;
	}

	public int getRegNo()
	{
		return regNo;
	}

	public void setRegNo(int regNo)
	{
		this.regNo = regNo;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
}

 
File : Bean Class
 

package com.simplecode.action;

public class Address
{
	private int houseNo;
	private String street;
	private String city;
	private String country;

	public int getHouseNo()
	{
		return houseNo;
	}

	public String getStreet()
	{
		return street;
	}

	public void setHouseNo(int houseNo)
	{
		this.houseNo = houseNo;
	}

	public void setStreet(String street)
	{
		this.street = street;
	}

	public String getCountry()
	{
		return country;
	}

	public void setCountry(String country)
	{
		this.country = country;
	}

	public String getCity()
	{
		return city;
	}

	public void setCity(String city)
	{
		this.city = city;
	}
}

 
In order to implement the above functionality via ajax, do read the article on CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
 
Do read :

 File : UserAction (Action Class)
 

package com.simplecode.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction implements Action, ModelDriven<User>
{
	User user = new User();
	
	public User getUser()
	{
		return user;
	}
	
	public void setUser(User user)
	{
		this.user = user;
	}
	
	public String execute()
	{
		return SUCCESS;
	}
	
	public User getModel()
	{
		return user;
	}
}

 
In the above article I have used the concept of ModelDriven interface in struts2, if you are not aware of what model driven interface is, then please read the article on modeldriven interface here
 

Jsp Pages

 
File : index.jsp

<HTML>
<HEAD>
<title>Add/Remove dynamic rows</title>
<SCRIPT lang="javascript">
	function addRow(tableID)
	{
		var table = document.getElementById(tableID);

		var rowCount = table.rows.length;
		var row = table.insertRow(rowCount);
		var counts = rowCount - 1;

		var cell1 = row.insertCell(0);
		var houseNo = document.createElement("input");
		houseNo.type = "text";
		houseNo.name = "addresses[" + counts + "].houseNo";
		cell1.appendChild(houseNo);

		var cell2 = row.insertCell(1);
		var street = document.createElement("input");
		street.type = "text";
		street.name = "addresses[" + counts + "].street";
		cell2.appendChild(street);

		var cell3 = row.insertCell(2);
		var city = document.createElement("input");
		city.type = "text";
		city.name = "addresses[" + counts + "].city";
		cell3.appendChild(city);

		var cell4 = row.insertCell(3);
		var country = document.createElement("input");
		country.type = "text";
		country.name = "addresses[" + counts + "].country";
		cell4.appendChild(country);

	}
</SCRIPT>
</HEAD>
<BODY>

<form action="submit" method="post">
<table>
<tr>
<td>
Reg No
</td>
<td>      :</td>
<td><INPUT type="text" name="regNo" /></td>
</tr>
<tr>
<td>Name</td>
<td>      :</td>
<td><INPUT type="text" name="name" /></td>
</tr>
<tr><td><br/><b>Addresses</b></td>
</tr>

</table>
 

<TABLE id="addressesTable">
	<TR>
		<TD>House No</TD>
		<TD>Street</TD>
		<TD>City</TD>
		<TD>Country</TD>
	</TR>
	<TR>
		<TD><INPUT type="text" name="addresses[0].houseNo" /></TD>
		<TD><INPUT type="text" name="addresses[0].street" /></TD>
		<TD><INPUT type="text" name="addresses[0].city" /></TD>
		<TD><INPUT type="text" name="addresses[0].country" /></TD>
	</TR>
</TABLE>
<INPUT type="button" value="Add More" onclick="addRow('addressesTable')" />
<input type="submit" value="SUBMIT" />
</form>
</BODY>
</HTML>

 
File : result.jsp

<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>User Details</title>
</head>
<body>
	<h1>User information</h1>
	ID : <s:property value="regNo" /><br />
	Name : <s:property value="name" /><br />
	Addresses :
	
<table>
<tr>
    <td width="10%">Reg No :</td>
    <td width="15%" >Street :</td>
    <td width="15%" >City :</td>
    <td width="15%">Country :</td>
</tr>

<s:iterator value="addresses">
<tr>
    <td width="10%"><s:property value="houseNo" /></td>
    <td width="15%" ><s:property value="street"/></td>
    <td width="15%" ><s:property value="city"/></td>
    <td width="15%"><s:property value="country"/></td>
</tr>
</s:iterator>
</table>
	
</body>
</html>

 
Recommended reading :

 

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="submit" class="com.simplecode.action.UserAction">
            <result name="success">result.jsp</result>
        </action>
    </package>
</struts>

 

Run it

 
On running the application
 
Collection values
 
Input
 
Input collection
 
Output
 
Collection output
 
** UPDATE: Struts 2 Complete tutorial now available here.
 

Read More

Datetime picker in struts 2 using jquery

Posted by in Struts-2 | 4 comments

Feature jquery struts 2

Last time when I worked out how to get the dojo datetimepicker Well, it faced some issues like, I could not customize the size of the text box, and also its appearance. As an alternative I found out a plugin Struts2- Jquery which provide a lots of customizing features.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
To create a date time pick component in struts 2, please follow this two steps :
 
1. Add struts2-jquery-plugin-3.6.1.jar in your class path.
2. Include the “struts-jquery-tags” tag and its header in your jsp page
 

<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
<head>
<sj:head  />
</head>

 
Do read :

 

Feature of jquery

 
Simple Calculator

<sj:datepicker id="1" name="simpleCalander" displayFormat="dd-mm-yy" label="Simple Calander"/>

 
Simple jquery calander
 
Calander with change year Option

<sj:datepicker id="2" name="changeYear" displayFormat="dd-mm-yy" changeYear="true"
label="Change Year"/>

 
change year in struts 2 + jquery
 
Calander with ChangeYear and Monthyear Option

<sj:datepicker id="3" name="changeYearAndMonth" label="Change Month and Year"
 changeMonth="true" changeYear="true"/>

 

jquery with change year and month in struts 2
 

Calander with Button Pannel Option

<sj:datepicker id="5" name="withPannel" label="With Button Panel" showButtonPanel="true"/>

 
j query with button pannel in struts 2
 

Calander with Show Seconds Option

<sj:datepicker id="4"  name="showSeconds"  label="Show Seconds" timepicker="true"
 timepickerShowSecond="true" timepickerFormat="hh:mm:ss"/>

 

jquery with show second option
 
Now lets see the complete example
 

Jsp Page

 
File: datepicker.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>

<html>
<head>
<title>Date Picker</title>
<sj:head  />
</head>

<body>
<h3>Struts2 Date Picker example</h3>
<s:form action="dateTimePicker" theme="xhtml">
<sj:datepicker id="1" name="simpleCalander" displayFormat="dd-mm-yy" label="SimpleCalander"/>
<sj:datepicker id="2" name="changeYear"  displayFormat="dd-mm-yy" changeYear="true"
   label="ChangeYear"/>
<sj:datepicker id="3" name="changeYearAndMonth"
	label="Change Month and Year" changeMonth="true" changeYear="true" />
<sj:datepicker id="4" name="showSeconds" label="Show Seconds"
	timepicker="true" timepickerShowSecond="true" timepickerFormat="hh:mm:ss" />
<sj:datepicker id="5" name="withPannel" label="With Button Panel" showButtonPanel="true" />
<sj:datepicker id="6" name="slideDownEffect"
label="With fast slideDown Animation" showAnim="slideDown" duration="fast" />
<sj:datepicker id="7" name="fadeInEffect"
	label="With slow fadeIn Animation" showAnim="fadeIn"
		showOptions="{direction: 'up' }" duration="slow" />
<sj:datepicker id="8" name="yearRage" label="Show Years only from 2000 until 2020"
 yearRange="2000:2020" changeYear="true" />
<sj:datepicker id="9" name="withOutButton" label="Without Button" showOn="focus" />

<s:submit value="submit" name="submit" />
</s:form>
</body>
</html>

 
File: result.jsp
 

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Date Picker Result</title>
</head>
<body>
	<h3>Struts2 Date Picker using Jquery</h3>
	simpleCalander : <s:property value="simpleCalander" />
	<br />
	changeYear : <s:property value="changeYear" />
	<br />
	changeYearAndMonth : <s:property value="changeYearAndMonth" />
	<br />

	showSeconds : <s:property value="showSeconds" />
	<br />
	withPannel : <s:property value="withPannel" />
	<br />
	slideDownEffect : <s:property value="slideDownEffect" />
	<br />
	fadeInEffect : <s:property value="fadeInEffect" />
	<br />
	yearRage : <s:property value="yearRage" />
	<br />
	withOutButton : <s:property value="withOutButton" />
	<br />
	      
</body>
</html>

 

Action Class

 

package com.simplecode.action;

import com.opensymphony.xwork2.Action;

public class DatePickerAction implements Action {

	private String simpleCalander;
	private String changeYear;
	private String changeYearAndMonth;
	private String showSeconds;
	private String withPannel;
	private String slideDownEffect;
	private String fadeInEffect;
	private String yearRage;
	private String withOutButton;

	public String getSimpleCalander() {
		return simpleCalander;
	}

	public String getChangeYear() {
		return changeYear;
	}

	public String getChangeYearAndMonth() {
		return changeYearAndMonth;
	}

	public String getShowSeconds() {
		return showSeconds;
	}

	public String getWithPannel() {
		return withPannel;
	}

	public String getSlideDownEffect() {
		return slideDownEffect;
	}

	public String getFadeInEffect() {
		return fadeInEffect;
	}

	public String getYearRage() {
		return yearRage;
	}

	public String getWithOutButton() {
		return withOutButton;
	}

	public void setSimpleCalander(String simpleCalander) {
		this.simpleCalander = simpleCalander;
	}

	public void setChangeYear(String changeYear) {
		this.changeYear = changeYear;
	}

	public void setChangeYearAndMonth(String changeYearAndMonth) {
		this.changeYearAndMonth = changeYearAndMonth;
	}

	public void setShowSeconds(String showSeconds) {
		this.showSeconds = showSeconds;
	}

	public void setWithPannel(String withPannel) {
		this.withPannel = withPannel;
	}

	public void setSlideDownEffect(String slideDownEffect) {
		this.slideDownEffect = slideDownEffect;
	}

	public void setFadeInEffect(String fadeInEffect) {
		this.fadeInEffect = fadeInEffect;
	}

	public void setYearRage(String yearRage) {
		this.yearRage = yearRage;
	}

	public void setWithOutButton(String withOutButton) {
		this.withOutButton = withOutButton;
	}

	public String execute() {
		return SUCCESS;
	}
}

 

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="" namespace="/jsp" extends="struts-default">
<action name="dateTimePicker" class="com.simplecode.action.DatePickerAction" method="execute">
  <result name="success">/jsp/result.jsp</result>
</action>
</package>
</struts>

 

Demo

 
On running the application:-
 
DateTime Using Jquery
 
download

Read More
Page 4 of 10«First...23456...10...Last»