should I make two different servlet entry for rest and normal html in web.xml

倖福魔咒の 提交于 2020-01-06 14:12:55

问题


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!


回答1:


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.




回答2:


It is up to you to design the server side of the infrastructure.

Neither the RESTful specifications have any instructions for doing this nor the Servlet specifications enforce anything on this.

On the Applications design I think it is better idea to keep two different servlets to handle different URLs because over time the classes will become complex and long. These to may be used as front controllers and may have common logic class in the backend.



来源:https://stackoverflow.com/questions/26375573/should-i-make-two-different-servlet-entry-for-rest-and-normal-html-in-web-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!