Monday, 25 September 2017

Ajax Call in Spring MVC Portlet

Today we will discuss how to use Ajax in Spring Portlet. For this we create two select box one for country and second for States. When someone select country Ajax call is generated and dynamically add options in States select box depending on which country is selected.Before reading this blog it is highly recommended to read my previous blog Spring Portlet in Liferay and Form Handling in Spring Portlet .
Lets Start this step by step:-





Step 1:-Create Spring MVC Portlet
For creating a basic Spring MVC portlet you can refer my previous blog Spring MVC Portlet in liferay.

Step 2:-Attach jquery in Portlet
For using jquery open liferay-portlet.xml and in header javascript attachjquery.min.js

Ex-
<header-portlet-javascript>
   http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
</header-portlet-javascript>

Also put requires-namespaced-parameters is false inside liferay-portlet.xml.

Ex-
<requires-namespaced-parameters>
    false
</requires-namespaced-parameters>
Step 3:-Create Ajax in your view.jsp
Open view.jsp and paste this content:-

view.jsp
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:resourceURL id="findState" var="findState" ></portlet:resourceURL>
<script type="text/javascript">
$(document).ready(function(){
$( "#country" ).change(function() {
$.ajax({
url: "${findState}" ,
type: 'POST',
datatype:'json',
data: {
countryName: $("#country").val()
},
success: function(data){
var content= JSON.parse(data);
$('#state').html('');// to clear the previous option
$.each(content, function(i, state) {
$('#state').append($('<option>').text(state.name).attr('value', state.stateId));
});
}
});
});
});
</script>
<b>Change the Country State Change By Ajax</b> <br><br>
Country:
<select id="country" name="country">
<option value="select">Select Country</option>
<option value="india">India</option>
<option value="usa">USA</option>
</select>
<br><br>
State:
<select id="state" name="state">
</select>
view rawview.jsp hosted with ❤ by GitHub

Explanation:-

1)In line 4 we create a resource Url findState ,this URL is used to create a method in our controller that is using this value as:-
@ResourceMapping(value="findState")

2)In Line 6 to 27 we create our Ajax call that can use URL findState and send the name of country in a parameter countryName. If data return successfully in the form of json we parse the json data and by using for loop append the data in state select box.

Step 3:-Handle the Ajax Call
Open your controller and create a method that is call when Ajax is generated.:-

AjaxController.java
package com.test;
import java.io.IOException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.ParamUtil;
@Controller(value = "AjaxController")
@RequestMapping("VIEW")
public class AjaxController {
@RenderMapping
public String handleRenderRequest(RenderRequest request,RenderResponse response, Model model) {
return "view";
}
@ResourceMapping(value="findState")
public void findStateForCountry(ResourceRequest request, ResourceResponse response) throws IOException {
String countryName = ParamUtil.getString(request, "countryName");
JSONArray stateArray = JSONFactoryUtil.createJSONArray();
JSONObject stateObject,stateObject2;
if(countryName.equalsIgnoreCase("india"))
{
stateObject = JSONFactoryUtil.createJSONObject();
stateObject.put("stateId", "1");
stateObject.put("name", "Delhi");
stateObject2 = JSONFactoryUtil.createJSONObject();
stateObject2.put("stateId", "2");
stateObject2.put("name", "Gujrat");
}
else{
stateObject = JSONFactoryUtil.createJSONObject();
stateObject.put("stateId", "21");
stateObject.put("name", "LA");
stateObject2 = JSONFactoryUtil.createJSONObject();
stateObject2.put("stateId", "22");
stateObject2.put("name", "California");
}
stateArray.put(stateObject);
stateArray.put(stateObject2);
response.getWriter().println(stateArray);
}
}
view rawAjaxController.java hosted with ❤ by GitHub

Explanation:-
1)Here we create a method findStateForCountry that is annotated with @ResourceMapping(value="findState") this find state must match with the id of resourceUrl that is created in view.jsp.

2)In method findStateForCountry we create a Json Array and two Json objects and put value in the json object on the basis of India or USA and return the response.In json object we add two property one is id of state and second is name of state.This array is iterated in view.jsp to create state drop down.


Output:-




Project Structure:-



You can download source code from Ajax in Spring  Portlet 

TEST

I am Java Developer. I have 6 year Experiance in this field and like to post in blogging. So keep sharing and like my post

0 comments:

Post a Comment

 

Copyright @ 2017 Liferay Article.