1 在pom.xml中导入依赖
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
在Spring-MVC.xml中
```java
<!--
proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。
为true则是基于类的代理将起作用(需要cglib库)
-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
### 在Spring-security.xml文件中开启注解
```java
<security:global-method-security jsr250-annotations="enabled"/>
4 JSR-250注解使用
-
@RolesAllowed表示访问对应方法时所应该具有的角色
示例: @PostAuthorize 示例: @RolesAllowed({"USER", "ADMIN"}) 该方法只要具有"USER", "ADMIN"任意一种权限就可以访问。这里可以省 略前缀ROLE_,实际的权限可能是ROLE_ADMIN
-
@PermitAll表示允许所有的角色进行访问,也就是说不进行权限控制
-
@DenyAll是和PermitAll相反的,表示无论什么角色都不能访问
4.1 在Controller添加权限
@RolesAllowed("ADMIN")
@RequestMapping("/findProductByParams")
public String findProductByParams(@RequestParam(name = "page" ,defaultValue = "1") int pageNum,
@RequestParam(name = "size" ,defaultValue = "2") int pageSize,
Product product,Model model){
List<Product> productList = productService.findProductByParams(product,pageNum,pageSize);
PageInfo pageInfo = new PageInfo(productList);
model.addAttribute("pageInfo", pageInfo);
return "product-list";
}
@RolesAllowed(“ADMIN”) 在方法上findProductByParams使用代表的是只有ADMIN的权限才能访问该功能
5 对用户权限的遍历方法
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userMapper.login(s);
UserDetails details = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),getAuth(user.getRoleList()));
return details;
}
public List<GrantedAuthority> getAuth(List<Role> roleList){
List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
for (Role r : roleList){
list.add(new SimpleGrantedAuthority(r.getRoleName()));
}
return list;
}