我正在将Spring Security 3.1和Spring 3.2用于REST服务。我正在努力使每个响应都是JSON,例如,如果用户尝试访问某些资源但尚未通过身份验证。另外,如果用户发出错误的请求,我想返回带有错误消息的JSON。
只需提一下,将某个全局位置放置在我应该捕获所有错误/异常的位置会更容易接受。
为什么不编写一个由所有其他控制器扩展的控制器类(或者在使用3.2的情况下使用@ControllerAdvice),并在该类中包含一个带有异常处理程序注释的方法?像这样
@ExceptionHandler(Throwable.class)
public @ResponseBody GenericResponse handleException(Throwable throwable){
//handle exception
}
或阅读此博客文章
更新
很抱歉收到这个延迟回复。这是我的建议。使它仅以403响应失败。为此,只需在您的spring安全配置中添加以下代码段即可。
<beans:bean id="entryPoint"
class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
并将entrypoint-ref指向此bean
<http auto-config="true" use-expressions="true" entry-point-ref="entryPoint">
然后在客户端的AJAX代码中添加一个错误块
error : function( jqXHR, textStatus, errorThrown ){
if (jqXHR.status == 403){
alert('you need to login to do this operation');
window.location.href = contextPath+"/signin";
// or whatever you want to
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句