I am a beginner in liferay portlet development and I am developing a portlet that receives a http get request, processes some information and than it has to return a json object. My problem is that my portlet sends a whole html page instead of just the json object. This is my 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 this in the doView() method I know that this is not the best practice, but I am not concerned with that at the moment. Can someone explain to me how to return just the json object I read something about serveResponse, but I couldn't figure out how to invoke it.
Well, one thing to notice, that the
doView()
is mostly responsible for rendering of your portlet. Your requirement can better achieved by1 -
processAction
(Portlet Action) or2 -
serveResource
(Portlet AJAX service).To my view, AJAX request-response will be the most suitable case; for that you just need to create a resource URL on your portlet view. Like:
Add a JavaScript method to the page, from where you can generate AJAX request to your portlet. The method will look something like this,
Call that ajax method on a button / link click event:
And finally, in your portlet's action listener class add the following
serveResource
method, responsible for handling AJAX based request(s).Here you can get your request parameters and generate a response in the sense you want:
Thats it! Hope, this will be helpful for you :)