在服务器端我们可以通过Spring security提供的注解对方法来进行权限控制(主要有3种方式)。Spring Security在方法的权限控制上
支持三种类型的注解,JSR-250注解、@Secured注解和支持表达式的注解,这三种注解默认都是没有启用的,需要单独通过global-method-security元素的对应属性进行启用。
1.JSR-250注解介绍
(1)spring-security.xml中添加注解的开启:
<security:global-method-security jsr250-annotations="enabled"> </security:global-method-security>
(2)在pom.xml中导入相关的依赖:
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
(3)在ProductController的方法上设置:
//查询全部产品
@RequestMapping("/findAll.do")
@RolesAllowed("ADMIN")//只有具有admin权限的用户登录才可以查看全部产品,如果这个用户没有admin的权限,点击页面会出现403权限不足的信息,因此要配置友好的页面见(4)
public ModelAndView findAll() throws Exception {
ModelAndView mv = new ModelAndView();
List<Product> ps = productService.findAll();
mv.addObject("productList", ps);
mv.setViewName("product-list1");
return mv;
}
补充:
对于JSR-250注解来说,在controller中@RolesAllowed("ADMIN"),可以省略前面的ROLE_,但是在@Secured注解中就不可以省略。
(4)在web.xml中配置:
<error-page> <error-code>403</error-code> <location>/403.jsp</location> </error-page>
[email protected]注解介绍
@Secured注解是spring security默认提供的,因此不需要在web。xml中导入依赖。
3.支持表达式的注解介绍
只有用户名是tom的用户可以进行用户的添加,其他任何角色都不行,只有权限有admin的角色可以进行查询所有用户。