call a servlet from a JSP ?

Avatar

Avatar

18Harry

Avatar

18Harry

18Harry

15-10-2015

Hi EveryOne ,

I have a servlet that uses some request parameters and based on that sets a JSON Response.

Is it possible to use this in my JSP (I do not have a form) .

 

I want to invoke the servlet by passing the parameters and obtain the JSON Response and display this content on my JSP. I dont want to copy the same code to my JSP because this servlet is already being used by several classes and hence would like re-use the same.

 

Thanks in  Advance

Harish

View Entire Topic

Avatar

Avatar

JohnFait

Avatar

JohnFait

JohnFait

15-10-2015

You can use SlingRequestProcessor.

http://sling.apache.org/apidocs/sling6/org/apache/sling/engine/SlingRequestProcessor.html

You can try something like the following;

private RequestResponseFactory requestResponseFactory;

private SlingRequestProcessor requestProcessor;

 private ResourceResolver resourceResolver;

 

 private JSONObject getResourceJSON(Resource resource, Map<String, Object> anyOtherRequestParams) {
        JSONObject jsonObject = null;
        String requestURL = null;
        try {
                requestURL = resource.getPath() + ".json";
                HttpServletRequest request = this.requestResponseFactory.createRequest("GET", requestURL, anyOtherRequestParams);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                HttpServletResponse response = requestResponseFactory.createResponse(out);
                this.requestProcessor.processRequest(request, response, this.resourceResolver);
                jsonObject = new JSONObject(new String(out.toByteArray(), STRING_ENCODING));           
        } catch (Exception ex) {
            LOGGER.warn("Failed to export resource as JSON " + resource + "," + requestURL, ex);
        }
        return jsonObject;
    }