Should I create two different servlet entries for normal rest and HTML in web.xml

advertisements

I am writing spring mvc application.

In my application I have web pages as well as rest web services to handle ajax call.

I have done below entry in web.xml

<servlet>
    <servlet-name>myapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring_myapp-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>myapp</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

Should I map my rest url with same servlet like

<servlet-mapping>
    <servlet-name>myapp</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Or should I make new servlet entry for rest.

I have done required entries in pom.xml for "org.codehaus.jackson" and also I have made required entries in my spring_myapp-servlet.xml.

For html page I am using below code in my controller

@RequestMapping(value = "/htmlUrl")
public ModelAndView ModifyValiodation(HttpServletRequest request) {
     // my code
}

For rest service I am using

@RequestMapping(value = "/restUrl")
public @ResponseBody Map<String, String> restUrl(HttpServletRequest request) {
     // my code
}

If I am using only one servlet for two url mapping, then total 4 url will be made.

  1. myapp/htmlUrl.html
  2. myapp/restUrl.html
  3. myapp/rest/htmlUrl
  4. myapp/rest/restUrl

If I am using two different servlet with individual dispacherServlet then will i have to make entry of every component and service of spring in both the servlet.xml?

Please point out the solution for exposing rest web service.

Thanks!


use

<servlet-mapping>
 <servlet-name>myapp</servlet-name>
 <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

If you use two DispatcherServlet entries , it will load two ApplicationContext Objects in your application. Since you are using spring mvc to handle all the requests to your app, you should be fine with this configuration. Any request url that ends with .html or any urls that contains /rest/ will be handled by spring.