Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

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');"  />


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


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...