在spring security 3中,对于某些须要保护的url,能够很容易地实现当没权限的时候, redirect到一个页面(好比自定义的404.jsp页面)进行显示没权限的信息; 但有的时候,必需要对一些AJAX的请求url也同时判断其是否有权限输出; 若是没权限的话,通常要以JSON的方式返回给用户端,好比弹出一个提示框,显示没权限; 在SPRING security 3中,当没权限的时候,会由spring security 本身的拦截器 AccessDeniedHandler 进行拦截的,所以,能够在这个地方进行扩展自定义, 而后统一返回给前端的都是json的方式,而且在前端的jquery js中,扩展jquery post的 方法,若是对json返回的结果中,有相关“没权限操做”的信息,则弹出错误提示框, 这样,只须要在要用到$ajax提交的页面中,引入js就能够了,下面看代码实现。 1) 首先,实现AccessDeniedHandler 类; [code="java"] public class MyAccessDeniedHandlerImpl implements AccessDeniedHandler { public MyAccessDeniedHandlerImpl() { } public String getAccessDeniedUrl() { return accessDeniedUrl; } public void setAccessDeniedUrl(String accessDeniedUrl) { this.accessDeniedUrl = accessDeniedUrl; } public MyAccessDeniedHandlerImpl(String accessDeniedUrl) { this.accessDeniedUrl=accessDeniedUrl; } private String accessDeniedUrl; @Override public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException reason) throws ServletException, IOException { boolean isAjax = "XMLHttpRequest".equals(req.getHeader("X-Requested-With")); //若是是ajax请求 if (isAjax) { String jsonObject = "{\"message\":\"You are not privileged to request this resource.\","+ // "\"access-denied\":true,\"cause\":\"AUTHORIZATION_FAILURE\"}"; String contentType = "application/json"; resp.setContentType(contentType); String jsonObject="noright"; PrintWriter out = resp.getWriter(); out.print(jsonObject); out.flush(); out.close(); return; } else { String path = req.getContextPath(); String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path+"/"; resp.sendRedirect(basePath+accessDeniedUrl); } } [/code] 在上面的处理中,判断若是是ajax处理,则输出json字符串给客户端,不然就 redirect到指定的accessDeniedUrl, 2) 在applicationContext-security.xml中进行设置,以下: [code="java"] <http auto-config="true"> <intercept-url pattern="/admin*" access="ROLE_ADMIN" /> <access-denied-handler ref="accessDeniedHandler"/> </http> <beans:bean id="accessDeniedHandler" class="com.test.MyAccessDeniedHandlerImpl"> <beans:property name="accessDeniedUrl" value="403.jsp" /> </beans:bean> [/code] 3) springsecurity.js [code="java"] (function($){ // 保存原有的jquery ajax; var $_ajax = $.ajax; $.ajax = function(options){ var originalSuccess, mySuccess, success_context; if (options.success) { // save reference to original success callback originalSuccess = options.success; success_context = options.context ? options.context : $; // 自定义callback mySuccess = function(data) { if (data['access-denied']) { if (data.cause==='AUTHENTICATION_FAILURE') { alert('登陆超时,请从新登陆.'); window.location.href = contextPath + '/'; } else if (data.cause==='AUTHORIZATION_FAILURE') { if (data=="noright") { alert('对不起,你没有访问该资源的权限.'); } } return; // call original success callback originalSuccess.apply(success_context, arguments); }; // override success callback with custom implementation options.success = mySuccess; } // call original ajax function with modified arguments $_ajax.apply($, arguments); }; })(jQuery); [/code]