Reputation: 14717
I am doing a Spring web application and I am using spring security 3.1.
I need to create a subclass of SimpleUrlAuthenticationFailureHandler. And I need to load localized strings in the inherited method
public void onAuthenticationFailure(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response,
AuthenticationException exception)
throws IOException,
javax.servlet.ServletException
I need to set loaded localized strings in HTTP request or session.
I already defined the following
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
However, in the above onAuthenticationFailure method, WebApplicationContext is not available. And I got the following error
No WebApplicationContext found: not in a DispatcherServlet request?
if I do the following in onAuthenticationFailure:
WebApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request);
Locale locale = RequestContextUtils.getLocale(request);
String msg = ctx.getMessage(msgCode, new Object[]{}, locale);
How can I use the messages defined in the above messageSource in onAuthenticationFailure ?
Thanks a lot!
Regards.
Upvotes: 1
Views: 383
Reputation: 18194
You don't need to get application context manually. All you need is to let spring autowire the required dependency:
@Autowire
private MessageSource messageSource;
However be aware, that the security related beans are in the root web application context. This means that your messageSource
definition also needs to be in the root context (not in the servlet application context).
If you really want to pull your dependency manually, you can use (but that is unnecessary overhead):
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
Upvotes: 3