Reputation: 677
I am new to Sling framework. Is there any way we can call different methods.
For ex - on Page I have add,delete, edit button so apart from creating three files i can create three methods(add, delete,update) in same file.
Please suggest.
I tried by changing the method name
@Property(name = "sling.servlet.methods", value = { "getData" })
But it is not working
@Service
@Properties({
@Property(name = "sling.servlet.paths", value = { "getData" }),
@Property(name = "sling.servlet.methods", value = { "GET" })
})
public class getData extends SlingAllMethodsServlet {
Upvotes: 0
Views: 2837
Reputation: 326
The SlingAllMethodsServlet
will support any of the valid HTTP verbs as methods and in response to a request will call the appropriate do
method. For instance, in response to a PUT
request the doPut
method will be called.
In your case if you wanted your servlet to support both getting data and creating new data, you would want to allow methods GET
and POST
and implement the doGet
and doPost
methods.
@Service
@Properties( {
@Property(name = "sling.servlet.paths", value = { "/getData" } ),
@Property(name = "sling.servlet.methods", value = { "GET", "POST" } )
} )
public class DataServlet extends SlingAllMethodsServlet {
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) { ... }
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) { ... }
}
To add delete and edit support as well you would simply need to support the DELETE
and PUT
HTTP verbs along with implementing the doDelete
and doPut
methods in your servlet.
A tangentially related note - by using the @SlingServlet
annotation in place of the @Service and @Component annotations you can shorten the code a bit and get better autocompletion and documentation support.
Upvotes: 3