Reputation: 3518
Including libs/foundation/global.jsp
at the top of my jsp winds up calling <cq:defineObjects />
, which winds up instantiating the slingRequest or currentNode variables that I can use within my scriptlets. However, I am creating beans and including them like so
<jsp:useBean id="myBean" class="com.foo.bar.MyBean" />
<jsp:setProperty name="myBean" property="request" value="<%= slingRequest %>" />
and in my bean I have a getter/setter
public SlingHttpServletRequest getRequest() {
return resource;
}
public void setRequest(SlingHttpServletRequest request) {
this.resource = resource;
}
Here I'm instantiating the bean and passing in a reference to the current request.
My quesion is, how can I avoid having to pass in this parameter? Is there a way to get a reference to the current request via some sort of static context so that I can set the bean property in the constructor?
Upvotes: 1
Views: 2019
Reputation: 10241
You should never pass your request object to Bean classes. I agree with Thomas and Tomek's answer.
But starting to use a framework all of a sudden in the middle of a project to solve this issue is an overkill.
The basic idea here is that the request object should not be passed around. Rather, you should get the resource URI from the request and pass that to your Bean classes.
Additionally you can pass ResourceResolver object to get any resource in your Bean class.
My sample code would look something like this :
<jsp:useBean id="myBean" class="com.foo.bar.MyBean" />
<jsp:setProperty name="myBean" property="resourcePath" value="<%= slingRequest.getResourceURI() %>" />
<jsp:setProperty name="myBean" property="resourceResolver" value="<%= slingRequest.getResourceResolver() %>" />
and my Bean class method would be like this :
public SlingHttpServletRequest getResourcePath() {
return resourcePath;
}
public void setResourceResolver(String resourcePath) {
this.resourcePath = resourcePath;
}
public SlingHttpServletRequest getResourceResolver() {
return resolver;
}
public void setResourceResolver(ResourceResolver resovler) {
this.resolver = resolver;
}
Now in your bean class, you can form the resource object using the resourcePath and ResourceResolver like this :
Resource resource = resourceResolver.resolve(resourcePath);
Upvotes: 0
Reputation: 9304
There is no way to statically pass the request to newly created bean (and there can't be, as there might be many requests at the same time, so we can't have a shared static variable to store it). You may create a scriptlet:
<% pageContext.setAttribute("myBean", new MyBean(slingRequest)); %>
MyBean property: ${myBean.property}
or get rid of the beans and use one of the frameworks mentioned by Thomas:
Upvotes: 1