The Below code will show you how you can create the service in Liferay and how you can call that services using javascript.
- For this, First you have to create service builder(service.xml) to build service using ant build-service command.
service.xml
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 6.2.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_6_2_0.dtd">
<service-builder package-path="com.evon">
<author>manish</author>
<namespace>JSONService</namespace>
<entity name="Employee" local-service="true" remote-service="true">
<!-- PK fields -->
<column name="empId" type="long" primary="true" />
<!-- Other fields -->
<column name="empname" type="String" />
<column name="empaddress" type="String" />
<!-- Order -->
<order by="asc">
<order-column name="empname" />
</order>
</entity>
</service-builder>
- After successful build of service.xml file open EmployeeServiceImpl and create your own service method.
public class EmployeeServiceImpl extends EmployeeServiceBaseImpl {
public Employee getEmployee(long emplyeeId)
throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException {
return EmployeeLocalServiceUtil.getEmployee(emplyeeId);
}
}
Then we need to run service builder using ant build-service command or from eclipse ant view we can run same command.
- To Access your Service using the JavaScript you can write the code in your view.jsp
view.jsp
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<aui:script>
Liferay.provide(window,'getDetails',function() {
Liferay.Service(
'/JSONServiceDemo-portlet.employee/get-employee',
{
emplyeeId: $('#<portlet:namespace />empId').val()
},
function(obj) {
alert(JSON.stringify(obj));
console.log(obj);
}
);
});
</aui:script>
<aui:input type="text" id="empId" name="empId" />
<aui:button type="button" value="Click" onClick="getDetails();" />
- Now Deploy that portlet in liferay server.
Note: In my case the portlet name is JSONServiceDemo-portlet.
Finally enter the employee Id in text box then click on button it can return the employee detail in JSON format.
0 Comment(s)