在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]