Search code examples
javaspringservletsweb-applicationsodata

Multiple odata servlets and endpoints - is it possible?


I am using oData servlets for my web application and would like to add additional endpoints for it.

For example: /odata/* And also: /pathVariable/{pathVariable}/odata/*

while "pathVariable" serv me for passing additional data and variables.

I tried duplicating the servlet method and direct it to a new URL mapping unsuccessfully.

This is my current code:

@Bean
public ServletRegistrationBean odataServlet() {
    ServletRegistrationBean<CXFNonSpringJaxrsServlet> odataServlet = new ServletRegistrationBean<>(new CXFNonSpringJaxrsServlet(), "/odata/*");
    Map<String, String> initParameters = new HashMap<>();
    initParameters.put("javax.ws.rs.Application", "org.apache.olingo.odata2.core.rest.app.ODataApplication");
    initParameters.put("org.apache.olingo.odata2.service.factory", "com.context.JPAServiceFactory");
    odataServlet.setInitParameters(initParameters);
    return odataServlet;
}

My expected result is multiple endpoints available for oData use:

/odata

/pathName/data/odata/*


Solution

  • Are you trying to create 2 different servlets as 2 different and distinct OData services?

    If so, you can try defining your OData servlets and their endpoints by using javax's @WebServlet annotation and letting Spring scan for them.

    For example, 1st service:

    @WebServlet(urlPatterns = {"/odata/*"}, initParams = {
            @WebInitParam(name = "javax.ws.rs.Application", value = "org.apache.olingo.odata2.core.rest.app.ODataApplication"),
            @WebInitParam(name = "org.apache.olingo.odata2.service.factory", value = "com.context.JPAServiceFactory")
    })
    public class MyODataServlet extends ODataServlet {
    
    }
    

    And 2nd service:

    @WebServlet(urlPatterns = {"/another-odata/*"}, initParams = {
            @WebInitParam(name = "javax.ws.rs.Application", value = "org.apache.olingo.odata2.core.rest.app.ODataApplication"),
            @WebInitParam(name = "org.apache.olingo.odata2.service.factory", value = "com.context.JPAServiceFactory")
    })
    public class AnotherODataServlet extends ODataServlet {
    
    }
    

    Just don't forget to scan them both by using:

    @Configuration
    @ComponentScan(basePackages = {
            <packages of JPAServiceFactory and other requires beans>
    })
    @ServletComponentScan(basePackages = <the web servlets package>)
    public class ODataConfig {
    
    }