2024年6月14日发(作者:)

spring security自定义AccessDeniedHandler

在Spring默认的AccessDeniedHandler中只有对页面请求的处理,而没有对Ajax的处理。而在项目开发是Ajax又是

我们要常用的技术,所以我们可以通过自定义AccessDeniedHandler来处理Ajax请求。我们在Spring默认的

AccessDeniedHandlerImpl上稍作修改就可以了。

1.

2.

3.

4.

public class DefaultAccessDeniedHandler implements AccessDeniedHandler {

/* (non-Javadoc)

* @see DeniedHandler#handle(

ServletRequest, rvletResponse, DeniedExc

eption)

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

18.

19.

20.

21.

22.

23.

24.

25.

26.

27.

28.

));

29.

30.

}

}

*/

private String errorPage;

//~ Methods =========================================================

===============================================

public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedExcepti

on accessDeniedException)

throws IOException, ServletException {

boolean isAjax = Request(request);

if(isAjax){

Message msg = ion(accessDeniedException);

(response, msg);

}else if (!itted()) {

if (errorPage != null) {

// Put exception into request scope (perhaps of use to a view)

ribute(_DENIED_403, accessDeniedException);

// Set the 403 status code.

tus(_FORBIDDEN);

// forward to error page.

RequestDispatcher dispatcher = uestDispatcher(errorPage);

d(request, response);

} else {

ror(_FORBIDDEN, sage(

1 / 3

31.

32.

33.

34.

35.

36.

37.

38.

39.

40.

41.

42.

43.

44.

45.

46.

47.

48.

}

/**

* The error page to use. Must begin with a "/" and is interpreted relative to the current context root.

*

* @param errorPage the dispatcher path to display

*

* @throws IllegalArgumentException if the argument doesn't comply with the above limitations

*/

public void setErrorPage(String errorPage) {

if ((errorPage != null) && !With("/")) {

throw new IllegalArgumentException("errorPage must begin with '/'");

}

age = errorPage;

}

}

这里我们直接将异常信息通过PrintWriter输出到前台,然后在前台做统一的处理就可以了。

最后在配置文件中配置下

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

18.

default-target-url="/"/>

2 / 3