Question

I'm curious if there is a way to access a referrer resource from inside an OSGI Servlet.

Example:

  1. I have a form component
  2. Form component submits to /bin/form (a servlet)
  3. Inside the servlet at /bin/form I would like to access the form component Resource - not sure how to do this part

any ideas/thoughts would be greatly appreciated.

thank you, Brodie

Was it helpful?

Solution

You may add a hidden value with the component resource path:

<input type="hidden" name="resourcePath" value="${resource.path}"/>

value will be available as resourcePath parameter in the servlet code:

String resourcePath = request.getParameter("resourcePath");

You should check if the resource path is a valid value, as a malicious user can set anything they want there.

Also, please consider the second approach: instead of binding the servlet to a static path /bin/form you may bind it to your component resourceType. Let's assume that this resource type is myapp/component/form. In this case you may declare servlet as follows:

@SlingServlet(resourceTypes="myapp/component/form", methods="POST", selectors="form")
public FormServlet extends SlingAllMethodsServlet {
    public doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
        Resource formResource = request.getResource();
        // ...
    }
}

Form code should look like this:

<form action="${resource.path}.form.html" method="post">
    <!-- your form contents here -->
</form>

Advantages of this approach:

  • you can get the form resource as simply as request.getResource(),
  • you don't need to perform additional resource path parameter validation,
  • it is more RESTful.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top