String currentPage = request.getParameter((new ParamEncoder("tableId").encodeParameterName(TableTagParameters.PARAMETER_PAGE)));
Java, J2SE, J2ME, J2EE, ANDROID, JQUERY, JAVA SCRIPT, JSP, SERVLET, Collection Framework, Java Generics, C, C++
Friday, January 30, 2015
session-timeout in web.xml vs setMaxInactiveInterval method
WEB.XML
<session-config>
<session-timeout>10</session-timeout>
</session-config>
Info : session timeout configured in web.xml will be applied to whole application's all sessions.
Here session timeout has value in minutes. means all the sessions in the whole application will be terminated if user not performing any action on the respective session for 10mins
JAVA
mySession.setMaxInactiveInterval(10);
Info:
setMaxInactiveInterval() method takes value in seconds.
so here mySession will be terminated after 10sec.
Thursday, January 29, 2015
BOOTSTRAP : HOW TO SHOW BOOTSTRAP CONFIRMATION DIALOGUE
JSP
<html lang="en">
<head>
<script src="${pageContext.request.contextPath}/jquery/jquery.js"></script>
<script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.js"></script>
<script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap-tooltip.js"></script>
<script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap-confirmation.js"></script>
<a class="btn" data-href="/pkg/Pkg/delete?
pkgId=${pkgData.id}&pkgName=${pkgData.name}"
data-toggle="confirmation"
data-placement="left"
data-popout="true"
data-singleton="true"
data-original-title="" title="">
<img src="${pageContext.request.contextPath}/images/delete.jpg" />
</a>
</body>
</html>
JAVA SCRIPT
$(document).ready(function() {
$('[data-toggle="confirmation"]').confirmation({
title : 'Are you sure ?',
animation : true,
popout: true,
btnOkLabel : 'Yes',
btnCancelLabel : 'No',
onConfirm : function() {
},
onCancel : function() {
$('[data-toggle="confirmation"]').confirmation('hide');
}
});
<html lang="en">
<head>
<script src="${pageContext.request.contextPath}/jquery/jquery.js"></script>
<script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.js"></script>
<script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap-tooltip.js"></script>
<script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap-confirmation.js"></script>
</head>
<body>
<a class="btn" data-href="/pkg/Pkg/delete?
pkgId=${pkgData.id}&pkgName=${pkgData.name}"
data-toggle="confirmation"
data-placement="left"
data-popout="true"
data-singleton="true"
data-original-title="" title="">
<img src="${pageContext.request.contextPath}/images/delete.jpg" />
</a>
</body>
</html>
JAVA SCRIPT
$(document).ready(function() {
$('[data-toggle="confirmation"]').confirmation({
title : 'Are you sure ?',
animation : true,
popout: true,
btnOkLabel : 'Yes',
btnCancelLabel : 'No',
onConfirm : function() {
},
onCancel : function() {
$('[data-toggle="confirmation"]').confirmation('hide');
}
});
});
Wednesday, January 28, 2015
HOW TO DISPLAY ROW NUMBER IN DISPLAY TAG
<display:table id="pkgData" name="pkgsList" requestURI="/pkg/Pkg/search">
<display:column title="Sr.#" >${pkgData_rowNum}</display:column>
</display:table>
<display:column title="Sr.#" >${pkgData_rowNum}</display:column>
</display:table>
Tuesday, January 27, 2015
STRUTS2 UNKNOWN ACTION HANDLER CLASS (UnknownHandler)
struts.xml
<struts>
<bean type="com.opensymphony.xwork2.UnknownHandler" name="handler" class="com.raj.mv.pd.controller.pkg.UnknownActionController"/>
...
...
</struts>
UNKNOWN ACTION HANDLER
import org.apache.struts2.dispatcher.Dispatcher;
import com.raj.commons.logging.LogManager;
import com.raj.mv.pd.constants.Results;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.UnknownHandler;
import com.opensymphony.xwork2.XWorkException;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.config.RuntimeConfiguration;
import com.opensymphony.xwork2.config.entities.ActionConfig;
public class UnknownActionController implements UnknownHandler{
public static final String MODULE = UnknownActionController.class.getSimpleName();
@Override
public ActionConfig handleUnknownAction(String namespace, String actionName) throws XWorkException {
LogManager.getLogger().debug(MODULE,"Method called handleUnknownAction()");
ConfigurationManager configurationManager = Dispatcher.getInstance().getConfigurationManager();
RuntimeConfiguration runtimeConfiguration = configurationManager.getConfiguration().getRuntimeConfiguration();
ActionConfig actionConfig = runtimeConfiguration.getActionConfig(namespace, actionName);
if(actionConfig == null) { // invalid url request, and this need to be handled
actionConfig = runtimeConfiguration.getActionConfig("", "pkg/Pkg/error");
}
return actionConfig;
}
@Override
public Object handleUnknownActionMethod(Object arg0, String arg1) throws NoSuchMethodException {
LogManager.getLogger().debug(MODULE,"Method called handleUnknownActionMethod()");
return Results.EXCEPTION;
}
@Override
public Result handleUnknownResult(ActionContext arg0, String arg1, ActionConfig arg2, String arg3) throws XWorkException {
LogManager.getLogger().debug(MODULE,"Method called handleUnknownResult()");
return null;
}
}
<struts>
<bean type="com.opensymphony.xwork2.UnknownHandler" name="handler" class="com.raj.mv.pd.controller.pkg.UnknownActionController"/>
...
...
</struts>
UNKNOWN ACTION HANDLER
import org.apache.struts2.dispatcher.Dispatcher;
import com.raj.commons.logging.LogManager;
import com.raj.mv.pd.constants.Results;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.UnknownHandler;
import com.opensymphony.xwork2.XWorkException;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.config.RuntimeConfiguration;
import com.opensymphony.xwork2.config.entities.ActionConfig;
public class UnknownActionController implements UnknownHandler{
public static final String MODULE = UnknownActionController.class.getSimpleName();
@Override
public ActionConfig handleUnknownAction(String namespace, String actionName) throws XWorkException {
LogManager.getLogger().debug(MODULE,"Method called handleUnknownAction()");
ConfigurationManager configurationManager = Dispatcher.getInstance().getConfigurationManager();
RuntimeConfiguration runtimeConfiguration = configurationManager.getConfiguration().getRuntimeConfiguration();
ActionConfig actionConfig = runtimeConfiguration.getActionConfig(namespace, actionName);
if(actionConfig == null) { // invalid url request, and this need to be handled
actionConfig = runtimeConfiguration.getActionConfig("", "pkg/Pkg/error");
}
return actionConfig;
}
@Override
public Object handleUnknownActionMethod(Object arg0, String arg1) throws NoSuchMethodException {
LogManager.getLogger().debug(MODULE,"Method called handleUnknownActionMethod()");
return Results.EXCEPTION;
}
@Override
public Result handleUnknownResult(ActionContext arg0, String arg1, ActionConfig arg2, String arg3) throws XWorkException {
LogManager.getLogger().debug(MODULE,"Method called handleUnknownResult()");
return null;
}
}
Monday, January 26, 2015
STRUTS2 Display exception detail on the JSP
To Display exception message
<s:label label="Exception :" value='%{exception}' />
To Display exception stack stack
<s:label label="Exception :" value='%{exceptionStack}' />
<s:label label="Exception :" value='%{exception}' />
To Display exception stack stack
<s:label label="Exception :" value='%{exceptionStack}' />
Wednesday, January 21, 2015
STRUTS2 AJAX AND JSON BASED VALIDATION
struts.xml
<package name="validationPkg" namespace="/validate" extends="json-default">
<interceptors>
<interceptor name="transaction" class="com.raj.controller.interceptor.TransactionInterceptor" />
</interceptors>
<action name="*/*/*" class="com.raj.controller.{1}.{2}CTRL" method="{3}">
<interceptor-ref name="basicStack"></interceptor-ref>
<interceptor-ref name="transaction"/>
<result type="json">
<param name="root">validationMessage</param>
</result>
</action>
</package>
Action Class
package com.raj.controller.pkg;
public class PkgCTRL extends ActionSupport {
private ValidationMessage validationMessage = new ValidationMessage();
public ValidationMessage getValidationMessage() {
return validationMessage;
}
public void setValidationMessage(ValidationMessage validationMessage) {
this.validationMessage = validationMessage;
}
public String doValidation(){
LogManager.getLogger().debug(MODULE,"Method called doValidation()");
PkgData pkgData = PkgDAO.getPkgByName(packageName);
getValidationMessage().setMessageCode(ValidationMessage.ERROR);
if( packageName == null || packageName.trim().length() == 0 ){
getValidationMessage().setMessage(getText("empty.name"));
}else if( packageName.matches(getText("name.validation.regex")) ){
if( pkgData != null ){
getValidationMessage().setMessage(getText("name.already.exist"));
}else{
getValidationMessage().setMessage("Valid Name");
getValidationMessage().setMessageCode(ValidationMessage.SUCCESS);
}
}else{
getValidationMessage().setMessage(getText("invalid.name"));
}
return Results.SUCCESS;
}
}
POJO CLASS
public class ValidationMessage {
public final static short SUCCESS = 1;
public final static short ERROR = 0;
private String message;
private short messageCode;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getMessageCode() {
return messageCode;
}
public void setMessageCode(short messageCode) {
this.messageCode = messageCode;
}
}
KEY ENUM
public enum ValidationKeys {
EMPTY_NAME("empty.name"),
NAME_VALIDATION_REGEX("name.validation.regex"),
NAME_ALREADY_EXIST("name.already.exist"),
INVALID_NAME("invalid.name"),
VALID_NAME("valid.name"),;
public String key;
ValidationKeys(String key){
this.key = key;
}
}
ApplicationResources_en.properties
#Ajax validation messages
invalid.name = Invalid Name (Only alphanumeric Allowed)
empty.name = Empty Name
name.already.exist = Name already exist
name.validation.regex = ^[a-zA-Z0-9]*$
Validation Js file
/*
verifyUniqueness() require two arguments 'fieldId' and 'actionName', it makes an AJAX call to the
passed action's validation method and it return the appropriate result message.
Invalid fielId message will be displayed in red color and valid fielId message will be displayed in green color.
Here 'actionName' value will be like '/validate/pkg/Pkg/validation'
in this action value '/validate' is the namespace value in struts.xml file and remaining value will be mapped dynamically to the respective
action's method through wildcard used in the struts.xml file.
*/
function verifyUniqueness(fieldId,actionName){
var pkgNameVal = $("#"+fieldId).val();
clearErrorMessages(null);
$.ajax({
type: "POST",
url: contextPath+actionName,
data: {packageName:pkgNameVal},
success: function(data){
if(data.messageCode == "1"){
// success code logic
}else{
// error code logic
}
callback(data);
},
error: function(data){
console.log(data);
}
});
}
function callback(data){
console.log(data);
}
JSP FILE FIELD
<s:textfield name="pkgData.name" key="getText('pkg.name')" id="pkgName" cssClass="form-control" onblur="verifyUniqueness('pkgName','/validate/pkg/Pkg/doValidation');" />
<package name="validationPkg" namespace="/validate" extends="json-default">
<interceptors>
<interceptor name="transaction" class="com.raj.controller.interceptor.TransactionInterceptor" />
</interceptors>
<action name="*/*/*" class="com.raj.controller.{1}.{2}CTRL" method="{3}">
<interceptor-ref name="basicStack"></interceptor-ref>
<interceptor-ref name="transaction"/>
<result type="json">
<param name="root">validationMessage</param>
</result>
</action>
</package>
Action Class
package com.raj.controller.pkg;
public class PkgCTRL extends ActionSupport {
private ValidationMessage validationMessage = new ValidationMessage();
public ValidationMessage getValidationMessage() {
return validationMessage;
}
public void setValidationMessage(ValidationMessage validationMessage) {
this.validationMessage = validationMessage;
}
public String doValidation(){
LogManager.getLogger().debug(MODULE,"Method called doValidation()");
PkgData pkgData = PkgDAO.getPkgByName(packageName);
getValidationMessage().setMessageCode(ValidationMessage.ERROR);
if( packageName == null || packageName.trim().length() == 0 ){
getValidationMessage().setMessage(getText("empty.name"));
}else if( packageName.matches(getText("name.validation.regex")) ){
if( pkgData != null ){
getValidationMessage().setMessage(getText("name.already.exist"));
}else{
getValidationMessage().setMessage("Valid Name");
getValidationMessage().setMessageCode(ValidationMessage.SUCCESS);
}
}else{
getValidationMessage().setMessage(getText("invalid.name"));
}
return Results.SUCCESS;
}
}
POJO CLASS
public class ValidationMessage {
public final static short SUCCESS = 1;
public final static short ERROR = 0;
private String message;
private short messageCode;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getMessageCode() {
return messageCode;
}
public void setMessageCode(short messageCode) {
this.messageCode = messageCode;
}
}
KEY ENUM
public enum ValidationKeys {
EMPTY_NAME("empty.name"),
NAME_VALIDATION_REGEX("name.validation.regex"),
NAME_ALREADY_EXIST("name.already.exist"),
INVALID_NAME("invalid.name"),
VALID_NAME("valid.name"),;
public String key;
ValidationKeys(String key){
this.key = key;
}
}
ApplicationResources_en.properties
#Ajax validation messages
invalid.name = Invalid Name (Only alphanumeric Allowed)
empty.name = Empty Name
name.already.exist = Name already exist
name.validation.regex = ^[a-zA-Z0-9]*$
Validation Js file
/*
verifyUniqueness() require two arguments 'fieldId' and 'actionName', it makes an AJAX call to the
passed action's validation method and it return the appropriate result message.
Invalid fielId message will be displayed in red color and valid fielId message will be displayed in green color.
Here 'actionName' value will be like '/validate/pkg/Pkg/validation'
in this action value '/validate' is the namespace value in struts.xml file and remaining value will be mapped dynamically to the respective
action's method through wildcard used in the struts.xml file.
*/
function verifyUniqueness(fieldId,actionName){
var pkgNameVal = $("#"+fieldId).val();
clearErrorMessages(null);
$.ajax({
type: "POST",
url: contextPath+actionName,
data: {packageName:pkgNameVal},
success: function(data){
if(data.messageCode == "1"){
// success code logic
}else{
// error code logic
}
callback(data);
},
error: function(data){
console.log(data);
}
});
}
function callback(data){
console.log(data);
}
JSP FILE FIELD
<s:textfield name="pkgData.name" key="getText('pkg.name')" id="pkgName" cssClass="form-control" onblur="verifyUniqueness('pkgName','/validate/pkg/Pkg/doValidation');" />
Tuesday, January 20, 2015
HOW TO USE ENUM IN STRUTS2 SELECT TAG
Set OGNL (Object-Graph Navigation Language ) true in struts.xml file
struts.xml
<constant name="struts.ognl.allowStaticMethodAccess" value="true" />
Enum
package com.raj.controller.pkg;
public enum PkgStatusConstants {
ACTIVE("Active"),
INACTIVE("Inactive");
public final String val;
PkgStatusConstants(String val){
this.val = val;
}
}
Select Tag in Jsp
<s:select name="pkgData.status" key="getText('pkg.status')" list="@com.raj.controller.pkg.PkgStatusConstants@values()" cssClass="form-control" />
Keep Visiting
Write your Comment
Monday, January 19, 2015
How to make AJAX call to Struts2 action class method using Wildcard in struts.xml file
STRUTS.XML
<package name="validationPkg" namespace="/validate" extends="json-default">
<interceptors>
<interceptor name="transaction" class="com.raj.TransactionInterceptor" />
</interceptors>
<action name="*/*/*" class="com.raj.controller.{1}.{2}CTRL" method="{3}">
<interceptor-ref name="basicStack"></interceptor-ref>
<interceptor-ref name="transaction"/>
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
ACITON CLASS METHOD
private String packageName;
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(String responseText) {
this.inputStream = new ByteArrayInputStream(responseText.getBytes());
}
public String doValidation(){
PkgData pkgData = PkgDAO.getPkgByName(packageName);
if( packageName==null || packageName.trim().length()==0 ){
setInputStream("<div style='color:red;'> Empty Name");
}else if( packageName.matches(NVSMXUtility.NAME_VALIDATION_REGEX_PATTERN) ){
if( pkgData != null ){
setInputStream("<div style='color:red;'> Name already exist</div>");
}else{
setInputStream("<div style='color:green;'> Valid Name</div>");
}
}else{
setInputStream("<div style='color:red;'> Invalid Name (Only alphanumeric allowed)</div>");
}
return Results.SUCCESS;
}
JAVA SCRIPT
function verifyUniqueness(fieldName,actionName){
var pkgNameVal = $("#"+fieldName).val();
$.ajax({
type: "POST",
url: '/nvsmx/'+actionName,
data: {packageName:pkgNameVal},
success: function(data){
$("#message").show();
$("#message").html(data);
}
});
}
JSP
<s:textfield name="pkgData.name" id="pkgName" onblur="verifyUniqueness('pkgName','/validate/pkg/Pkg/doValidation');" />
<package name="validationPkg" namespace="/validate" extends="json-default">
<interceptors>
<interceptor name="transaction" class="com.raj.TransactionInterceptor" />
</interceptors>
<action name="*/*/*" class="com.raj.controller.{1}.{2}CTRL" method="{3}">
<interceptor-ref name="basicStack"></interceptor-ref>
<interceptor-ref name="transaction"/>
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
ACITON CLASS METHOD
private String packageName;
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(String responseText) {
this.inputStream = new ByteArrayInputStream(responseText.getBytes());
}
public String doValidation(){
PkgData pkgData = PkgDAO.getPkgByName(packageName);
if( packageName==null || packageName.trim().length()==0 ){
setInputStream("<div style='color:red;'> Empty Name");
}else if( packageName.matches(NVSMXUtility.NAME_VALIDATION_REGEX_PATTERN) ){
if( pkgData != null ){
setInputStream("<div style='color:red;'> Name already exist</div>");
}else{
setInputStream("<div style='color:green;'> Valid Name</div>");
}
}else{
setInputStream("<div style='color:red;'> Invalid Name (Only alphanumeric allowed)</div>");
}
return Results.SUCCESS;
}
JAVA SCRIPT
function verifyUniqueness(fieldName,actionName){
var pkgNameVal = $("#"+fieldName).val();
$.ajax({
type: "POST",
url: '/nvsmx/'+actionName,
data: {packageName:pkgNameVal},
success: function(data){
$("#message").show();
$("#message").html(data);
}
});
}
JSP
<s:textfield name="pkgData.name" id="pkgName" onblur="verifyUniqueness('pkgName','/validate/pkg/Pkg/doValidation');" />
Monday, January 12, 2015
STRUTS2 Interceptor to manage Hibernate Transcation
package com.raj.nvsmx.pd.controller.interceptor;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.raj.commons.logging.LogManager;
import com.raj.nv.pd.constants.Results;
import com.raj.nv.pd.model.HibernateSessionFactory;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.PreResultListener;
/**
* @author kirpalsinh.raj
* This Interceptor class is used to begin/commit/rollback Hibernate session transaction as per the result returned from the action classes.
*
*/
public class TransactionInterceptor extends BaseInterceptor {
private static final long serialVersionUID = 1L;
private static final String MODULE = TransactionInterceptor.class.getSimpleName();
Transaction transaction = null;
Session session = null;
String actionName;
@Override
public String intercept(ActionInvocation parentActionInvocation) throws Exception {
try {
session = HibernateSessionFactory.getSession();
transaction = session.beginTransaction();
actionName = parentActionInvocation.getProxy().getActionName();
parentActionInvocation.addPreResultListener( new PreResultListener() {
@Override
public void beforeResult(ActionInvocation childActionInvocation, String result) {
if (transaction != null && Results.SUCCESS.equalsIgnoreCase(result)) {
transaction.commit();
LogManager.getLogger().info(MODULE,"Transaction committed successfully for action "+actionName);
} else {
rollbackTranscation();
}
}
});
return parentActionInvocation.invoke();
} catch (Exception ex) {
LogManager.getLogger().error(MODULE,"Transaction Failed for action "+actionName+". Reason: " + ex.getMessage());
rollbackTranscation();
return Results.ERROR;
} finally {
closeSession();
}
}
public void rollbackTranscation(){
LogManager.getLogger().warn(MODULE,"Rollback Transaction for action "+actionName);
try {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
} catch (Exception ex) {
LogManager.getLogger().error(MODULE,"Failed to Rollback Transaction for action "+actionName+". Reason: " + ex.getMessage());
}
}
public void closeSession(){
try {
if (session != null) {
session.close();
}
} catch (HibernateException ex) {
LogManager.getLogger().error(MODULE,"Failed to close Session for action "+actionName+". Reason: " + ex.getMessage());
}
}
}
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.raj.commons.logging.LogManager;
import com.raj.nv.pd.constants.Results;
import com.raj.nv.pd.model.HibernateSessionFactory;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.PreResultListener;
/**
* @author kirpalsinh.raj
* This Interceptor class is used to begin/commit/rollback Hibernate session transaction as per the result returned from the action classes.
*
*/
public class TransactionInterceptor extends BaseInterceptor {
private static final long serialVersionUID = 1L;
private static final String MODULE = TransactionInterceptor.class.getSimpleName();
Transaction transaction = null;
Session session = null;
String actionName;
@Override
public String intercept(ActionInvocation parentActionInvocation) throws Exception {
try {
session = HibernateSessionFactory.getSession();
transaction = session.beginTransaction();
actionName = parentActionInvocation.getProxy().getActionName();
parentActionInvocation.addPreResultListener( new PreResultListener() {
@Override
public void beforeResult(ActionInvocation childActionInvocation, String result) {
if (transaction != null && Results.SUCCESS.equalsIgnoreCase(result)) {
transaction.commit();
LogManager.getLogger().info(MODULE,"Transaction committed successfully for action "+actionName);
} else {
rollbackTranscation();
}
}
});
return parentActionInvocation.invoke();
} catch (Exception ex) {
LogManager.getLogger().error(MODULE,"Transaction Failed for action "+actionName+". Reason: " + ex.getMessage());
rollbackTranscation();
return Results.ERROR;
} finally {
closeSession();
}
}
public void rollbackTranscation(){
LogManager.getLogger().warn(MODULE,"Rollback Transaction for action "+actionName);
try {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
} catch (Exception ex) {
LogManager.getLogger().error(MODULE,"Failed to Rollback Transaction for action "+actionName+". Reason: " + ex.getMessage());
}
}
public void closeSession(){
try {
if (session != null) {
session.close();
}
} catch (HibernateException ex) {
LogManager.getLogger().error(MODULE,"Failed to close Session for action "+actionName+". Reason: " + ex.getMessage());
}
}
}
Keep Visiting :)
Write your comment buddy
Thursday, January 8, 2015
STRUTS2 JQURY PLUGIN + STRUTS2 JSON PLUGIN EXAMPLE
OUTPUT
JSP
<%@taglib uri="/struts-jquery-tags" prefix="sj"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<sj:head jquerytheme="flick" jqueryui="true" />
</head>
<script>
$(document).ready(function() {
$('#states').change(function(event) {
var state = $("select#states").val();
$.getJSON('/nvsmx/jsonSelectAction.action', {
stateName : state
}, function(jsonResponse) {
$('#message').text(jsonResponse.message);
var select = $('#cities');
select.find('option').remove();
$.each(jsonResponse.cityMap, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
});
});
});
</script>
<body>
<h1>Welcome to AJAX + JSON</h1>
<sj:tabbedpanel id="localtabs" cssClass="list">
<sj:tab id="tab1" target="tone" label="Ajax" />
<sj:tab id="tab2" target="ttwo" label="getJSON" />
<sj:tab id="tab3" target="tthree" label="JSON-ACTION" />
<sj:tab id="tab4" target="tfour" label="JSON-SELECT" />
<div id="tone">
<sj:div id="resultDiv">
</sj:div>
<s:form id="form" namespace="/" action="ajax/Ajax/ajax" method="post">
<s:textfield id="id" name="id" value="1" label="ID" />
<br>
<sj:submit value="Submit" targets="resultDiv" />
</s:form>
</div>
<div id="ttwo">
<s:form id="form2" namespace="/" action="jsonMethoAction"
method="post">
<sj:submit value="JSON METHOD" />
</s:form>
</div>
<div id="tthree">
<s:form id="form3" namespace="/" action="jsonAction" method="post">
<sj:submit value="JSON ACTION" />
</s:form>
</div>
<div id="tfour">
<s:url var="remoteurl" namespace="/" value="/jsonAction.action"/>
<sj:select href="%{remoteurl}"
id="states"
name="states"
list="stateList"
emptyOption="false"
headerKey="-1"
headerValue="Please Select a Language"/>
<br><br><div id="message"></div>
<br><s:select id="cities" name="cities" list="{'Select State'}" label="City" />
</div>
</sj:tabbedpanel>
</body>
</html>
CONTROLLER/ACTION
;
1)
package com.el.nvsmx.pd.controller.json
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.opensymphony.xwork2.Action;
public class JsonCTRL {
private List<String> stateList = new ArrayList<String>();
private Map<String, String> cityMap = new HashMap<String, String>();
private String stateName;
private String message;
public String execute() {
System.out.println("CALLED EXECUTE()");
if ("Gujarat".equals(stateName)) {
setMessage("Welcome to GUJARAT");
getCityMap().put("1", "Anand");
getCityMap().put("2", "V.V.Nagar");
getCityMap().put("3", "Baroda");
getCityMap().put("4", "Ahmedabad");
} else if ("Rajasthan".equals(stateName)) {
setMessage("Welcome to Rajasthan");
getCityMap().put("1", "Jaipur");
getCityMap().put("2", "Udepur");
}
return Action.SUCCESS;
}
public String getJSON(){
getStateList().add("Gujarat");
getStateList().add("Rajasthan");
return execute();
}
public JsonCTRL(){
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Map<String, String> getCityMap() {
return cityMap;
}
public void setCityMap(Map<String, String> cityMap) {
this.cityMap = cityMap;
}
public List<String> getStateList() {
return stateList;
}
public void setStateList(List<String> stateList) {
this.stateList = stateList;
}
}
2)
package com.el.nvsmx.pd.controller.ajax;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.elitecore.nvsmx.policydesigner.constants.Results;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
public class AjaxCTRL extends ActionSupport implements ServletRequestAware,
ServletResponseAware, Preparable {
private static final long serialVersionUID = 1L;
private static final String MODULE = AjaxCTRL.class.getSimpleName();
private HttpServletRequest request;
private HttpServletResponse response;
private Map<String, String> stateMap = new LinkedHashMap<String, String>();
private List<String> dataList = new ArrayList<String>();
public String list() {
return Results.LIST;
}
public String getJSON() {
dataList.add("First");
return "Hello i am Json Result";
}
public String ajax() {
String key = request.getParameter("id");
String result = stateMap.get(key);
System.out.println("Name: " + result);
if (result == null) {
result = "Unknown";
}
try {
response.getWriter().write("your are in " + result + " state of INDIA.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
@Override
public void prepare() throws Exception {
System.out.println("Called prepare()");
if (stateMap.size() == 0) {
System.out.println("Initializing Map");
stateMap.put("1", "Kerala");
stateMap.put("2", "Tamil Nadu");
stateMap.put("3", "Jammu Kashmir");
stateMap.put("4", "Assam");
stateMap.put("5", "Gujarat");
stateMap.put("6", "Goa");
stateMap.put("7", "Maharastra");
stateMap.put("8", "Rajasthan");
}
}
}
STRUTS.XML
<package name="jsonnvsmx" namespace="/" extends="json-default">
<action name="jsonMethoAction" class="com.el.nvsmx.pd.controller.ajax.AjaxCTRL">
<result type="json" />
</action>
<action name="jsonAction" class="com.el.nvsmx.pd.controller.json.JsonCTRL">
<result type="json" />
</action>
<action name="jsonSelectAction" class="com.el.nvsmx.pd.controller.json.JsonCTRL">
<result type="json" />
</action>
<action name="ajaxJsonAction" class="com.el.nvsmx.pd.controller.json.JsonCTRL">
<result name="success" type="json" >/view/commons/Success.jsp</result>
</action>
</package>
Keep Visiting :)
Write your comment
Subscribe to:
Posts (Atom)
Scrum and Scrum master
Scrum Scrum is a framework which helps a team to work together. It is like a rugby team (the scrum name comes from rugby game). Scrum enco...
-
Docker: Docker is a tool/system/framework designed to make it easier to create, deploy, and run applications by using containers. Contain...
-
var beanPropertyArray = []; columnData = { "1": "One", "2": "Two", ...
-
Whenever an object of a POJO class is created then it will be in the Transient state An object in a Transient state doesn’t represent any...