在最新的Spring Security教程-Spring Security实现访问控制教程中,如果没有授权的用户访问加密的页面,默认的403页面就会展示
在本次教程中,我们教你两种自定义Spring Security 默认的403页面的方法
1.使用access-denied-handler标签
最简单的方法就是使用access-denied-handler标签,在“error-page”设置你自己的403页面
1
2
3
4
|
<http auto-config="true">
<intercept-url pattern="/admin*" access="ROLE_ADMIN" />
<access-denied-handler error-page="404"/>
</http>
|
2.实现AccessDeniedHandler类
第二种方法就是创建一个类并实现AccessDeniedHandler类,重写“handle()”方法,在里面设置你自己的访问逻辑
MyAccessDeniedHandler.java
1
2
3
4
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
31
32
33
34
35
36
37
38
39
|
package com.mkyong.common.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
public class MyAccessDeniedHandler implements AccessDeniedHandler {
private String accessDeniedUrl;
public MyAccessDeniedHandler() {
}
public MyAccessDeniedHandler(String accessDeniedUrl) {
this.accessDeniedUrl = accessDeniedUrl;
}
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException,
ServletException {
response.sendRedirect(accessDeniedUrl);
request.getSession().setAttribute("message",
"You do not have permission to access this page!");
}
public String getAccessDeniedUrl() {
return accessDeniedUrl;
}
public void setAccessDeniedUrl(String accessDeniedUrl) {
this.accessDeniedUrl = accessDeniedUrl;
}
}
|
3.例子
下面假设是你自定义的403页面
403.jsp
1
2
3
4
5
6
|
<html>
<body>
<h1>HTTP Status 403 - Access is denied</h1>
<h3>Message : ${message}</h3>
</body>
</html>
|
现在假如没有权限的用户访问受保护的页面,你自定义的403页面就会展示:
原创文章,转载请注明出处:http://www.it161.com/article/javaDetail?articleid=140113232712
更多原创内容,请访问:http://www.it161.com/