i beginner in liferay portlet development , developing portlet receives http request, processes information , has return json object. problem portlet sends whole html page instead of json object. code:
httpservletresponse servletresponse = portalutil.gethttpservletresponse((renderresponse)); servletresponse.setheader("content-type", "application/json"); servletresponse.setcharacterencoding("application/json"); printwriter out = servletresponse.getwriter(); out.write(entityutils.tostring(responseentity)); out.flush(); out.close();
i execute in doview() method know not best practice, not concerned @ moment. can explain me how return json object read serveresponse, couldn't figure out how invoke it.
well, 1 thing notice, doview()
responsible rendering of portlet. requirement can better achieved by
1 - processaction
(portlet action) or
2 - serveresource
(portlet ajax service).
to view, ajax request-response suitable case; need create resource url on portlet view. like:
<portlet:resourceurl var="ajaxresourceurl" />
add javascript method page, can generate ajax request portlet. method this,
<script type="text/javascript"> function _callajax(val1, val2){ var url = '<%=ajaxresourceurl %>'; // pass resource url created using scriplet / el. jquery.ajax({ type : "post", url : url, cache:false, datatype: "json", data: { value1: val1, // parameters if want pass value2: val2 }, success : function(data){ // whatever want response data }, error : function(xmlhttprequest, textstatus, errorthrown){ alert(errorthrown); alert(textstatus); } }); }; </script>
call ajax method on button / link click event:
<input type="button" onclick="_callajax('val1', 'val2')" value="send" />
and finally, in portlet's action listener class add following serveresource
method, responsible handling ajax based request(s).
here can request parameters , generate response in sense want:
@override public void serveresource(resourcerequest request, resourceresponse response) throws portletexception,ioexception { string value1 = paramutil.getstring(request , "value1", "default"); // request parameters string value2 = paramutil.getstring(request , "value2", ""); printwriter writer = response.getwriter(); jsonobject jsonobject = new jsonobject(); jsonobject.put(string key, boolean/long/collection/double/map/object value); writer.write(jsonobject.tostring()); }
thats it! hope, helpful :)
Comments
Post a Comment