WebRequest and HttpServletRequest in Spring MVC

2020-08-23 04:14发布

问题:

What is the difference between the two? Both have a getParameter method as well as setAttribute method, then where comes the difference between the two?

1) Which one is better to use in general?

2) Please explain specific scenarios where they can be used.

回答1:

The javadoc of WebRequest is pretty clear on the subject:

Generic interface for a web request. Mainly intended for generic web request interceptors, giving them access to general request metadata, not for actual handling of the request.

(emphasis mine).

The javadoc links to WebRequestInterceptor, which says:

Interface for general web request interception. Allows for being applied to Servlet request as well as Portlet request environments, by building on the WebRequest abstraction.

So, basically, you should not use WebRequest except in a WebRequestInterceptor. And they introduced this interface in order to be able to write interceptors that apply to servlets and portlets. Other than that, if you really need access to the request in Spring MVC controllers, you should use the standard HttpServletRequest.