在最新的Spring Security教程-Spring Security實現訪問控制教程中,若是沒有受權的用戶訪問加密的頁面,默認的403頁面就會展現 html
在本次教程中,咱們教你兩種自定義Spring Security 默認的403頁面的方法 java
最簡單的方法就是使用access-denied-handler標籤,在「error-page」設置你本身的403頁面 web
1
2
3
4
|
<http auto-config="true">
<intercept-url pattern="/admin*" access="ROLE_ADMIN" />
<access-denied-handler error-page="404"/>
</http>
|
第二種方法就是建立一個類並實現AccessDeniedHandler類,重寫「handle()」方法,在裏面設置你本身的訪問邏輯 spring
MyAccessDeniedHandler.java jsp
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;
}
}
|
下面假設是你自定義的403頁面 ide
403.jsp this
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
url
更多原創內容,請訪問:http://www.it161.com/ spa