在Spring Security中,實現訪問控制或權限控制是很是容易實現的,請看下面的代碼片斷:html
1
2
3
|
<
http
auto-config
=
"true"
>
<
intercept-url
pattern
=
"/admin*"
access
=
"ROLE_ADMIN"
/>
</
http
>
|
它的意思是,只有「ROLE_ADMIN」權限的用戶能夠容許訪問「 /admin*」路徑,若是沒有權限的用戶訪問則會提示「http 403 access denied page」錯誤。java
本次教程中,咱們像你展現只有「ROLE_ADMIN」權限的用戶能夠訪問「/admin*」web
訪問控制須要Spring Security的核心包,請參考Spring+Spring Security+Maven 實現的一個Hello World例子 列出的jarspring
Spring MVC作控制器並返回一個「hello」視圖,這個你應該能夠理解的。app
WelcomeController.javaeclipse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package
com.mkyong.common.controller;
import
org.springframework.stereotype.Controller;
import
org.springframework.ui.ModelMap;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
@Controller
public
class
WelcomeController {
@RequestMapping
(value =
"/admin"
, method = RequestMethod.GET)
public
String welcomeAdmin(ModelMap model) {
model.addAttribute(
"message"
,
"Spring Security - ROLE_ADMIN"
);
return
"hello"
;
}
}
|
hello.jspjsp
1
2
3
4
5
6
7
8
|
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<
html
>
<
body
>
<
h3
>Message : ${message}</
h3
>
<
a
href
=
"<c:url value="
j_spring_security_logout" />" > Logout</
a
>
</
body
>
</
html
>
|
一下是Sprign Security所有的配置文件,只容許「eclipse」用戶能夠訪問「/hello」頁面ide
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
xsi:schemaLocation="http://www.springframework.org/schema/beans
<
http
auto-config
=
"true"
>
<
intercept-url
pattern
=
"/admin*"
access
=
"ROLE_ADMIN"
/>
<
logout
logout-success-url
=
"/admin"
/>
</
http
>
<
authentication-manager
>
<
authentication-provider
>
<
user-service
>
<
user
name
=
"it161"
password
=
"password"
authorities
=
"ROLE_USER"
/>
<
user
name
=
"eclipse"
password
=
"password"
authorities
=
"ROLE_ADMIN"
/>
</
user-service
>
</
authentication-provider
>
</
authentication-manager
>
</
beans:beans
>
|
http://localhost:8080/SpringMVC/adminui
1.默認的登錄頁面以下所示:url
2.若是用「it161」登錄時,就會提示「http 403 is access denied page」,由於it161是「ROLE_USER」權限
3.若是用「eclipse」登錄的話,「hello.jsp」就會展現,由於「eclipse」是「ROLE_ADMIN「權限。
默認的403頁面很是醜陋,請能夠閱讀本人自定義你的403頁面:Spring Security教程-Spring Security實現訪問控制
原創文章,轉載請註明出處:http://www.it161.com/article/javaDetail?articleid=140113230945
更多原創內容,請訪問:http://www.it161.com/