要使用shiro的注解,需要先在applicationContext中配置开启shiro的注解模式.
<!-- 开启Shiro注解 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--登录-->
<prop key="org.apache.shiro.authz.UnauthenticatedException">
redirect:/index/login.html
</prop>
<!--授权-->
<prop key="org.apache.shiro.authz.UnauthorizedException">
redirect:/unauthorized.html
</prop>
</props>
</property>
<property name="defaultErrorView" value="error/genericView"/>
</bean>
然后还有一个特别需要注意的是在spring-mvc的配置文件中一定要打开aop配置功能!如果不加会造成注解的不起作用.
<aop:aspectj-autoproxy proxy-target-class="true"/>
后台代码:
@Controller
@RequestMapping("/manage")
public class ManageController {
@Resource
private PictureService pictureService;
@RequestMapping("/pictureList")
public ModelAndView pictureList() {
List<Picture> pictures = pictureService.listAll();
ModelAndView mv = new ModelAndView();
mv.addObject("pictures", pictures);
mv.setViewName("manage/pictureList");
return mv;
}
//需要登录了的用户才能访问
@RequiresAuthentication
@RequestMapping("/addPicture")
public ModelAndView addPicture() {
ModelAndView mv = new ModelAndView();
mv.setViewName("manage/addPicture");
return mv;
}
//要有admin角色的用户才能插入图片
@RequiresRoles("admin")
@RequestMapping("/insertPic")
public ModelAndView insertPic(Picture picture, MultipartFile uploadPic,HttpSession session) throws IllegalStateException, IOException {
ModelAndView mv = new ModelAndView();
String picPath = session.getServletContext().getRealPath("/") + "images/pictures/";
String oldFileName = uploadPic.getOriginalFilename();
String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
File newFile = new File(picPath + sdf.format(date) + suffix);
picture.setPicAddr("images/pictures/" + sdf.format(date) + suffix);
uploadPic.transferTo(newFile);
System.out.println("最新插入的图片ID是:" + pictureService.insertPic(picture));
mv.setViewName("redirect:pictureList.html");
return mv;
}
}
这样,当插入图片的时候如果角色权限不足是不能访问的,会跳转到权限不足页面.
shiro的几个注解:
1. @RequiresAuthentication
要求当前Subject在当前session中验证通过才能被访问或调用.
2. @RequiresGuest
要求当前Subject是一个guest,也就是说,他们必须是在当前session中没有被验证或记住才能被访问或调用.
3. @RequiresPermissions(“account:create”)
要求当前的Subject被允许一个或多个权限,以便执行注解的方法.
多个的话用values={“”,””}来标识
4. @RequiresRoles(“administrator”)
要求当前Subject拥有的一个或多个角色,如果他们没有,那么方法不会被执行,并且会抛出AuthorizationException.
5. @RequiresUser
要求当前Subject是一个应用程序用户,才能被注解的类/实例/方法所访问或调用.一个应用程序用户被定义为拥有一个已知身份,或在当前session中由于通过验证被确认,或者在之前的session中”RememberMe”服务被记住.