1

我正在做一个 Spring web 应用程序,我正在使用 spring security 3.1。

我需要创建一个 SimpleUrlAuthenticationFailureHandler 的子类。我需要在继承的方法中加载本地化字符串

public void onAuthenticationFailure(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response,
        AuthenticationException exception)
 throws IOException,
        javax.servlet.ServletException

我需要在 HTTP 请求或会话中设置加载的本地化字符串。

我已经定义了以下

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages"/>
</bean>  

但是,在上面的 onAuthenticationFailure 方法中,WebApplicationContext 是不可用的。我收到以下错误

No WebApplicationContext found: not in a DispatcherServlet request?

如果我在 onAuthenticationFailure 中执行以下操作:

    WebApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request);
    Locale locale = RequestContextUtils.getLocale(request);
    String msg = ctx.getMessage(msgCode, new Object[]{}, locale);

如何在 onAuthenticationFailure 中使用上述 messageSource 中定义的消息?

非常感谢!

问候。

4

1 回答 1

3

您不需要手动获取应用程序上下文。您只需要让 spring 自动装配所需的依赖项:

@Autowire
private MessageSource messageSource;

但是请注意,与安全相关的 bean 位于根 Web 应用程序上下文中。这意味着您的messageSource定义还需要在根上下文中(而不是在 servlet 应用程序上下文中)。

如果您真的想手动提取依赖项,可以使用(但这是不必要的开销):

WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
于 2013-06-14T18:19:58.770 回答