public abstract class FrameworkServlet extends HttpServletBean implements ApplicationContextAware
This class offers the following functionality:
WebApplicationContext
instance per servlet. The servlet's configuration is determined
by beans in the servlet's namespace.
Subclasses must implement doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
to handle requests. Because this extends
HttpServletBean
rather than HttpServlet directly, bean properties are
automatically mapped onto it. Subclasses can override initFrameworkServlet()
for custom initialization.
Detects a "contextClass" parameter at the servlet init-param level,
falling back to the default context class,
XmlWebApplicationContext
, if not found. Note that, with the default
FrameworkServlet
, a custom context class needs to implement the
ConfigurableWebApplicationContext
SPI.
Accepts an optional "contextInitializerClasses" servlet init-param that
specifies one or more ApplicationContextInitializer
classes. The managed web application context will be
delegated to these initializers, allowing for additional programmatic configuration,
e.g. adding property sources or activating profiles against the context's
environment. See also ContextLoader
which
supports a "contextInitializerClasses" context-param with identical semantics for
the "root" web application context.
Passes a "contextConfigLocation" servlet init-param to the context instance, parsing it into potentially multiple file paths which can be separated by any number of commas and spaces, like "test-servlet.xml, myServlet.xml". If not explicitly specified, the context implementation is supposed to build a default location from the namespace of the servlet.
Note: In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files, at least when using Spring's default ApplicationContext implementation. This can be leveraged to deliberately override certain bean definitions via an extra XML file.
The default namespace is "'servlet-name'-servlet", e.g. "test-servlet" for a servlet-name "test" (leading to a "/WEB-INF/test-servlet.xml" default location with XmlWebApplicationContext). The namespace can also be set explicitly via the "namespace" servlet init-param.
As of Spring 3.1, FrameworkServlet
may now be injected with a web
application context, rather than creating its own internally. This is useful in Servlet
3.0+ environments, which support programmatic registration of servlet instances. See
FrameworkServlet(WebApplicationContext)
Javadoc for details.
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
,
setContextClass(java.lang.Class<?>)
,
setContextConfigLocation(java.lang.String)
,
setContextInitializerClasses(java.lang.String)
,
setNamespace(java.lang.String)
,
Serialized FormModifier and Type | Field and Description |
---|---|
static Class<?> |
DEFAULT_CONTEXT_CLASS
Default context class for FrameworkServlet.
|
static String |
DEFAULT_NAMESPACE_SUFFIX
Suffix for WebApplicationContext namespaces.
|
static String |
SERVLET_CONTEXT_PREFIX
Prefix for the ServletContext attribute for the WebApplicationContext.
|
logger
Constructor and Description |
---|
FrameworkServlet()
Create a new
FrameworkServlet that will create its own internal web
application context based on defaults and values provided through servlet
init-params. |
FrameworkServlet(WebApplicationContext webApplicationContext)
Create a new
FrameworkServlet with the given web application context. |
Modifier and Type | Method and Description |
---|---|
protected void |
applyInitializers(ConfigurableApplicationContext wac)
Delegate the WebApplicationContext before it is refreshed to any
ApplicationContextInitializer instances specified by the
"contextInitializerClasses" servlet init-param. |
protected LocaleContext |
buildLocaleContext(HttpServletRequest request)
Build a LocaleContext for the given request, exposing the request's
primary locale as current locale.
|
protected ServletRequestAttributes |
buildRequestAttributes(HttpServletRequest request,
HttpServletResponse response,
RequestAttributes previousAttributes)
Build ServletRequestAttributes for the given request (potentially also
holding a reference to the response), taking pre-bound attributes
(and their type) into consideration.
|
protected void |
configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) |
protected WebApplicationContext |
createWebApplicationContext(ApplicationContext parent)
Instantiate the WebApplicationContext for this servlet, either a default
XmlWebApplicationContext
or a custom context class , if set. |
protected WebApplicationContext |
createWebApplicationContext(WebApplicationContext parent)
Instantiate the WebApplicationContext for this servlet, either a default
XmlWebApplicationContext
or a custom context class , if set. |
void |
destroy()
Close the WebApplicationContext of this servlet.
|
protected void |
doDelete(HttpServletRequest request,
HttpServletResponse response)
Delegate DELETE requests to
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) . |
protected void |
doGet(HttpServletRequest request,
HttpServletResponse response)
Delegate GET requests to processRequest/doService.
|
protected void |
doOptions(HttpServletRequest request,
HttpServletResponse response)
Delegate OPTIONS requests to
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) , if desired. |
protected void |
doPost(HttpServletRequest request,
HttpServletResponse response)
Delegate POST requests to
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) . |
protected void |
doPut(HttpServletRequest request,
HttpServletResponse response)
Delegate PUT requests to
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) . |
protected abstract void |
doService(HttpServletRequest request,
HttpServletResponse response)
Subclasses must implement this method to do the work of request handling,
receiving a centralized callback for GET, POST, PUT and DELETE.
|
protected void |
doTrace(HttpServletRequest request,
HttpServletResponse response)
Delegate TRACE requests to
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) , if desired. |
protected WebApplicationContext |
findWebApplicationContext()
|
String |
getContextAttribute()
Return the name of the ServletContext attribute which should be used to retrieve the
WebApplicationContext that this servlet is supposed to use. |
Class<?> |
getContextClass()
Return the custom context class.
|
String |
getContextConfigLocation()
Return the explicit context config location, if any.
|
String |
getContextId()
Return the custom WebApplicationContext id, if any.
|
String |
getNamespace()
Return the namespace for this servlet, falling back to default scheme if
no custom namespace was set: e.g.
|
String |
getServletContextAttributeName()
Return the ServletContext attribute name for this servlet's WebApplicationContext.
|
protected String |
getUsernameForRequest(HttpServletRequest request)
Determine the username for the given request.
|
WebApplicationContext |
getWebApplicationContext()
Return this servlet's WebApplicationContext.
|
protected void |
initFrameworkServlet()
This method will be invoked after any bean properties have been set and
the WebApplicationContext has been loaded.
|
protected void |
initServletBean()
Overridden method of
HttpServletBean , invoked after any bean properties
have been set. |
protected WebApplicationContext |
initWebApplicationContext()
Initialize and publish the WebApplicationContext for this servlet.
|
boolean |
isEnableLoggingRequestDetails()
Whether logging of potentially sensitive, request details at DEBUG and
TRACE level is allowed.
|
void |
onApplicationEvent(ContextRefreshedEvent event)
Callback that receives refresh events from this servlet's WebApplicationContext.
|
protected void |
onRefresh(ApplicationContext context)
Template method which can be overridden to add servlet-specific refresh work.
|
protected void |
postProcessWebApplicationContext(ConfigurableWebApplicationContext wac)
Post-process the given WebApplicationContext before it is refreshed
and activated as context for this servlet.
|
protected void |
processRequest(HttpServletRequest request,
HttpServletResponse response)
Process this request, publishing an event regardless of the outcome.
|
void |
refresh()
Refresh this servlet's application context, as well as the
dependent state of the servlet.
|
protected void |
service(HttpServletRequest request,
HttpServletResponse response)
Override the parent class implementation in order to intercept PATCH requests.
|
void |
setApplicationContext(ApplicationContext applicationContext)
Called by Spring via
ApplicationContextAware to inject the current
application context. |
void |
setContextAttribute(String contextAttribute)
Set the name of the ServletContext attribute which should be used to retrieve the
WebApplicationContext that this servlet is supposed to use. |
void |
setContextClass(Class<?> contextClass)
Set a custom context class.
|
void |
setContextConfigLocation(String contextConfigLocation)
Set the context config location explicitly, instead of relying on the default
location built from the namespace.
|
void |
setContextId(String contextId)
Specify a custom WebApplicationContext id,
to be used as serialization id for the underlying BeanFactory.
|
void |
setContextInitializerClasses(String contextInitializerClasses)
Specify the set of fully-qualified
ApplicationContextInitializer class
names, per the optional "contextInitializerClasses" servlet init-param. |
void |
setContextInitializers(ApplicationContextInitializer<?>... initializers)
Specify which
ApplicationContextInitializer instances should be used
to initialize the application context used by this FrameworkServlet . |
void |
setDispatchOptionsRequest(boolean dispatchOptionsRequest)
Set whether this servlet should dispatch an HTTP OPTIONS request to
the
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) method. |
void |
setDispatchTraceRequest(boolean dispatchTraceRequest)
Set whether this servlet should dispatch an HTTP TRACE request to
the
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) method. |
void |
setEnableLoggingRequestDetails(boolean enable)
Whether to log request params at DEBUG level, and headers at TRACE level.
|
void |
setNamespace(String namespace)
Set a custom namespace for this servlet,
to be used for building a default context config location.
|
void |
setPublishContext(boolean publishContext)
Set whether to publish this servlet's context as a ServletContext attribute,
available to all objects in the web container.
|
void |
setPublishEvents(boolean publishEvents)
Set whether this servlet should publish a ServletRequestHandledEvent at the end
of each request.
|
void |
setThreadContextInheritable(boolean threadContextInheritable)
Set whether to expose the LocaleContext and RequestAttributes as inheritable
for child threads (using an
InheritableThreadLocal ). |
addRequiredProperty, createEnvironment, getEnvironment, getServletName, init, initBeanWrapper, setEnvironment
doHead, getLastModified, service
getInitParameter, getInitParameterNames, getServletConfig, getServletContext, getServletInfo, init, log, log
public static final String DEFAULT_NAMESPACE_SUFFIX
public static final Class<?> DEFAULT_CONTEXT_CLASS
XmlWebApplicationContext
public static final String SERVLET_CONTEXT_PREFIX
public FrameworkServlet()
FrameworkServlet
that will create its own internal web
application context based on defaults and values provided through servlet
init-params. Typically used in Servlet 2.5 or earlier environments, where the only
option for servlet registration is through web.xml
which requires the use
of a no-arg constructor.
Calling setContextConfigLocation(java.lang.String)
(init-param 'contextConfigLocation')
will dictate which XML files will be loaded by the
default XmlWebApplicationContext
Calling setContextClass(java.lang.Class<?>)
(init-param 'contextClass') overrides the
default XmlWebApplicationContext
and allows for specifying an alternative class,
such as AnnotationConfigWebApplicationContext
.
Calling setContextInitializerClasses(java.lang.String)
(init-param 'contextInitializerClasses')
indicates which ApplicationContextInitializer
classes should be used to
further configure the internal application context prior to refresh().
FrameworkServlet(WebApplicationContext)
public FrameworkServlet(WebApplicationContext webApplicationContext)
FrameworkServlet
with the given web application context. This
constructor is useful in Servlet 3.0+ environments where instance-based registration
of servlets is possible through the ServletContext.addServlet(java.lang.String, java.lang.String)
API.
Using this constructor indicates that the following properties / init-params will be ignored:
setContextClass(Class)
/ 'contextClass'setContextConfigLocation(String)
/ 'contextConfigLocation'setContextAttribute(String)
/ 'contextAttribute'setNamespace(String)
/ 'namespace'The given web application context may or may not yet be refreshed. If it (a) is an implementation
of ConfigurableWebApplicationContext
and (b) has not
already been refreshed (the recommended approach), then the following will occur:
ServletContext
and ServletConfig
objects will be delegated to
the application contextpostProcessWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext)
will be calledApplicationContextInitializers
specified through the
"contextInitializerClasses" init-param or through the setContextInitializers(org.springframework.context.ApplicationContextInitializer<?>...)
property will be applied.refresh()
will be calledConfigurableWebApplicationContext
, none of the above will occur under the
assumption that the user has performed these actions (or not) per his or her
specific needs.
See WebApplicationInitializer
for usage examples.
webApplicationContext
- the context to useinitWebApplicationContext()
,
configureAndRefreshWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext)
,
WebApplicationInitializer
public void setContextAttribute(@Nullable String contextAttribute)
WebApplicationContext
that this servlet is supposed to use.@Nullable public String getContextAttribute()
WebApplicationContext
that this servlet is supposed to use.public void setContextClass(Class<?> contextClass)
WebApplicationContext
.
When using the default FrameworkServlet implementation,
the context class must also implement the
ConfigurableWebApplicationContext
interface.
public Class<?> getContextClass()
public void setContextId(@Nullable String contextId)
@Nullable public String getContextId()
public void setNamespace(String namespace)
public String getNamespace()
public void setContextConfigLocation(@Nullable String contextConfigLocation)
@Nullable public String getContextConfigLocation()
public void setContextInitializers(@Nullable ApplicationContextInitializer<?>... initializers)
ApplicationContextInitializer
instances should be used
to initialize the application context used by this FrameworkServlet
.public void setContextInitializerClasses(String contextInitializerClasses)
ApplicationContextInitializer
class
names, per the optional "contextInitializerClasses" servlet init-param.public void setPublishContext(boolean publishContext)
This is especially handy during testing, although it is debatable whether it's good practice to let other application objects access the context this way.
public void setPublishEvents(boolean publishEvents)
ServletRequestHandledEvent
public void setThreadContextInheritable(boolean threadContextInheritable)
InheritableThreadLocal
).
Default is "false", to avoid side effects on spawned background threads. Switch this to "true" to enable inheritance for custom child threads which are spawned during request processing and only used for this request (that is, ending after their initial task, without reuse of the thread).
WARNING: Do not use inheritance for child threads if you are
accessing a thread pool which is configured to potentially add new threads
on demand (e.g. a JDK ThreadPoolExecutor
),
since this will expose the inherited context to such a pooled thread.
public void setDispatchOptionsRequest(boolean dispatchOptionsRequest)
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
method.
Default in the FrameworkServlet
is "false", applying
HttpServlet
's default behavior (i.e.enumerating
all standard HTTP request methods as a response to the OPTIONS request).
Note however that as of 4.3 the DispatcherServlet
sets this
property to "true" by default due to its built-in support for OPTIONS.
Turn this flag on if you prefer OPTIONS requests to go through the regular dispatching chain, just like other HTTP requests. This usually means that your controllers will receive those requests; make sure that those endpoints are actually able to handle an OPTIONS request.
Note that HttpServlet's default OPTIONS processing will be applied in any case if your controllers happen to not set the 'Allow' header (as required for an OPTIONS response).
public void setDispatchTraceRequest(boolean dispatchTraceRequest)
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
method.
Default is "false", applying HttpServlet
's
default behavior (i.e. reflecting the message received back to the client).
Turn this flag on if you prefer TRACE requests to go through the regular dispatching chain, just like other HTTP requests. This usually means that your controllers will receive those requests; make sure that those endpoints are actually able to handle a TRACE request.
Note that HttpServlet's default TRACE processing will be applied in any case if your controllers happen to not generate a response of content type 'message/http' (as required for a TRACE response).
public void setEnableLoggingRequestDetails(boolean enable)
By default set to false
so that request details are not shown.
enable
- whether to enable or notpublic boolean isEnableLoggingRequestDetails()
public void setApplicationContext(ApplicationContext applicationContext)
ApplicationContextAware
to inject the current
application context. This method allows FrameworkServlets to be registered as
Spring beans inside an existing WebApplicationContext
rather than
finding
a
bootstrapped
context.
Primarily added to support use in embedded servlet containers.
setApplicationContext
in interface ApplicationContextAware
applicationContext
- the ApplicationContext object to be used by this objectBeanInitializationException
protected final void initServletBean() throws ServletException
HttpServletBean
, invoked after any bean properties
have been set. Creates this servlet's WebApplicationContext.initServletBean
in class HttpServletBean
ServletException
- if subclass initialization failsprotected WebApplicationContext initWebApplicationContext()
Delegates to createWebApplicationContext(org.springframework.context.ApplicationContext)
for actual creation
of the context. Can be overridden in subclasses.
FrameworkServlet(WebApplicationContext)
,
setContextClass(java.lang.Class<?>)
,
setContextConfigLocation(java.lang.String)
@Nullable protected WebApplicationContext findWebApplicationContext()
WebApplicationContext
from the ServletContext
attribute with the configured name
. The
WebApplicationContext
must have already been loaded and stored in the
ServletContext
before this servlet gets initialized (or invoked).
Subclasses may override this method to provide a different
WebApplicationContext
retrieval strategy.
null
if not foundgetContextAttribute()
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent)
XmlWebApplicationContext
or a custom context class
, if set.
This implementation expects custom contexts to implement the
ConfigurableWebApplicationContext
interface. Can be overridden in subclasses.
Do not forget to register this servlet instance as application listener on the
created context (for triggering its callback
), and to call
ConfigurableApplicationContext.refresh()
before returning the context instance.
parent
- the parent ApplicationContext to use, or null
if noneXmlWebApplicationContext
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac)
protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent)
XmlWebApplicationContext
or a custom context class
, if set.
Delegates to #createWebApplicationContext(ApplicationContext).parent
- the parent WebApplicationContext to use, or null
if noneXmlWebApplicationContext
,
createWebApplicationContext(ApplicationContext)
protected void postProcessWebApplicationContext(ConfigurableWebApplicationContext wac)
The default implementation is empty. refresh()
will
be called automatically after this method returns.
Note that this method is designed to allow subclasses to modify the application
context, while initWebApplicationContext()
is designed to allow
end-users to modify the context through the use of
ApplicationContextInitializers
.
wac
- the configured WebApplicationContext (not refreshed yet)createWebApplicationContext(org.springframework.context.ApplicationContext)
,
initWebApplicationContext()
,
ConfigurableApplicationContext.refresh()
protected void applyInitializers(ConfigurableApplicationContext wac)
ApplicationContextInitializer
instances specified by the
"contextInitializerClasses" servlet init-param.
See also postProcessWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext)
, which is designed to allow
subclasses (as opposed to end-users) to modify the application context, and is
called immediately before this method.
wac
- the configured WebApplicationContext (not refreshed yet)createWebApplicationContext(org.springframework.context.ApplicationContext)
,
postProcessWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext)
,
ConfigurableApplicationContext.refresh()
public String getServletContextAttributeName()
The default implementation returns
SERVLET_CONTEXT_PREFIX + servlet name
.
@Nullable public final WebApplicationContext getWebApplicationContext()
protected void initFrameworkServlet() throws ServletException
ServletException
- in case of an initialization exceptionpublic void refresh()
public void onApplicationEvent(ContextRefreshedEvent event)
The default implementation calls onRefresh(org.springframework.context.ApplicationContext)
,
triggering a refresh of this servlet's context-dependent state.
event
- the incoming ApplicationContext eventprotected void onRefresh(ApplicationContext context)
This implementation is empty.
context
- the current WebApplicationContextrefresh()
public void destroy()
destroy
in interface Servlet
destroy
in class GenericServlet
ConfigurableApplicationContext.close()
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
service
in class HttpServlet
ServletException
IOException
protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
Will also be invoked by HttpServlet's default implementation of doHead
,
with a NoBodyResponse
that just captures the content length.
protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
.doPost
in class HttpServlet
ServletException
IOException
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
protected final void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
.doPut
in class HttpServlet
ServletException
IOException
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
protected final void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
.doDelete
in class HttpServlet
ServletException
IOException
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
, if desired.
Applies HttpServlet's standard OPTIONS processing otherwise, and also if there is still no 'Allow' header set after dispatching.
doOptions
in class HttpServlet
ServletException
IOException
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
, if desired.
Applies HttpServlet's standard TRACE processing otherwise.
doTrace
in class HttpServlet
ServletException
IOException
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
protected final void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
The actual event handling is performed by the abstract
doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
template method.
ServletException
IOException
@Nullable protected LocaleContext buildLocaleContext(HttpServletRequest request)
request
- current HTTP requestnull
if none to bindLocaleContextHolder.setLocaleContext(org.springframework.context.i18n.LocaleContext)
@Nullable protected ServletRequestAttributes buildRequestAttributes(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable RequestAttributes previousAttributes)
request
- current HTTP requestresponse
- current HTTP responsepreviousAttributes
- pre-bound RequestAttributes instance, if anynull
to preserve
the previously bound instance (or not binding any, if none bound before)RequestContextHolder.setRequestAttributes(org.springframework.web.context.request.RequestAttributes)
@Nullable protected String getUsernameForRequest(HttpServletRequest request)
The default implementation takes the name of the UserPrincipal, if any. Can be overridden in subclasses.
request
- current HTTP requestnull
if none foundHttpServletRequest.getUserPrincipal()
protected abstract void doService(HttpServletRequest request, HttpServletResponse response) throws Exception
The contract is essentially the same as that for the commonly overridden
doGet
or doPost
methods of HttpServlet.
This class intercepts calls to ensure that exception handling and event publication takes place.
request
- current HTTP requestresponse
- current HTTP responseException
- in case of any kind of processing failureHttpServlet.doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
,
HttpServlet.doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)