Question

I am trying to use Ajax with Spring Portlet 2.5 (I can't upgrade to higher version because I need to run tests on this one - therefore I can't use @ResourceMapping). So this is what I tried

<script type='text/javascript'>
    function <portlet:namespace />setCurrentDateTime() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                 //now what?
            }
        };
        xhr.open("GET", '${actionURL}', true);
        xhr.send();
    }
</script>

<table>
    <tr>
        <td><b><a href="# "onclick="<portlet:namespace />setCurrentDateTime();" style="color: black;" id="refreshLink">Refresh</a></b></td>
    </tr>
</table>
<br/>
<div id="<portlet:namespace />messageText">${date}</div>

By this code, action on the server side is correctly trigerred but I am not sure how do I refresh the messageText to have there updated value from the server.

This is my server side code

@RequestMapping
public ModelAndView defaultView(RenderRequest request, RenderResponse response) {
    String date = (String) request.getPortletSession().getAttribute("date");
    if (date == null) {
        return new ModelAndView("home");
    } else {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("date", date);
        return new ModelAndView("home", map);
    }
}

@RequestMapping(params = "action=getDateTime")
public void handleActionRequest(ActionRequest ar, ActionResponse ar1) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    ar.getPortletSession().setAttribute("date", sdf.format(new Date()));
}
Was it helpful?

Solution

Updating the contents of the messageText element would require adding the following into the JavaScript where you currently have "now what?":

document.getElementById("<portlet:namespace />messageText").innerHTML = xhr.responseText;

However, the larger problem is that you're attempting to use Ajax in a portlet with a version of Spring that only supports JSR 168 (Portlet Spec 1.0). Resource Requests, which are how Ajax calls are typically handled, were not introduced until JSR 286 (Portlet Spec 2.0).

Updating the JavaScript with my suggested code results in the entire portal page being added as the innerHTML of the messageText element, as the ActionRequest resulted in a full RenderRequest being triggered for the portlet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top