can we do ajax call of a servlet registered with resourceType?

Avatar

Avatar

AdobeID24

Avatar

AdobeID24

AdobeID24

28-12-2020

Very classic question bt not clear to me ..can we do ajax call of a servlet registered with resourceType?

 

I have read some article they talk about calling the page (which has that particular resourceType component )with selector( mentioned during servlet registration )will automatically trigger the servlet registered with that resource Type .

 

but wanted to know in AJAX respect can we do ajax call as we do for servlet registered with Path ?

 

Any real time scenerio will be helpful .

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar

Andrei_Dantsou

Avatar

Andrei_Dantsou

Andrei_Dantsou

28-12-2020

Hello @AdobeID24,

1. The servlet should be registered with the desired resource type:

@SlingServletResourceTypes(
resourceTypes = "/bin/target-resource-type",
methods = HttpConstants.METHOD_GET
)
public class SimpleServlet extends SlingAllMethodsServlet {

2. The resource with the corresponding resource type should be created, e.g. /content/trigger-servlet containing the property sling:resourceType with the value /bin/target-resource-type
Screenshot.png

 

3. The path of the resource from the point #2 should be requested via ajax:

$.ajax({
url: '/content/trigger-servlet',
type: 'GET'
...


Regards

Answers (3)

Answers (3)

Avatar

Avatar

Anudeep_Garnepudi

MVP

Avatar

Anudeep_Garnepudi

MVP

Anudeep_Garnepudi
MVP

28-12-2020

@AdobeID24 

Yes you can call. There is no difference in the way to hit the Servlet(path or resource type) from client side. 

Avatar

Avatar

shelly-goel

MVP

Avatar

shelly-goel

MVP

shelly-goel
MVP

29-12-2020

@AdobeID24 

I tried with the json extension (rather than html as I was referring earlier) in ajax as below:

@SlingServlet(resourceTypes = "<your resurceType>", selectors = "myselector",

extensions = "json", methods = "GET")

$.ajax({ type:"GET", url: "<resourcepath>/_jcr_content.myselector.json", ...});

If you're using 'page' as the resourcetype, you could replace your resourcetype in the servlet with "cq/page" and would not have to use ''_jcr_content" in the ajax url/path.

Avatar

Avatar

shelly-goel

MVP

Avatar

shelly-goel

MVP

shelly-goel
MVP

28-12-2020

@AdobeID24 

AFAIK when a servlet is registered with 'resourceType', it will be called if the respective component is invoked and servlet cannot be requested through ajax. If there's a need to call the same servlet with ajax too, then register it with 'path' as well.

 

As per the sling documentation, if you would specify both 'resourceType' and 'path' in the servlet, it would be registered both ways.

https://sling.apache.org/documentation/the-sling-engine/servlets.html

"If both are set, the servlet is registered using both ways"