ssm整合时,springmvc拦截器能实现细颗粒权限访问么,当用户没有权限时,通过URL访问网页会跳回登录或者跳到错误页面
代码如下:
第一步:创建SpringMVC拦截器,拦截所有需要进行权限验证的功能请求
?
<mvc:annotation-driven>
<!-- 静态资源访问 -->
<mvc:resources mapping="/static/**" location="/static/">
<!-- 拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器,顺序执行 -->
<mvc:interceptor>
<!-- 如果不配置或/**,将拦截所有的Controller -->
<mvc:mapping path="/**">
<!-- 在Freemarker界面展示之前做一些通用处理 -->
<bean class="xx.xxxx.core.web.FreeMarkerViewInterceptor"></bean>
</mvc:mapping>
</mvc:interceptor> </mvc:interceptors></mvc:resources></mvc:annotation-driven>
第二步:创建作用于Method级别的Annotation类,用于传入功能ID
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Permission {
/**
* 功能ID,该功能ID,对应数据库中的功能ID
* @return
* @version V1.0.0
* @date Jan 13, 2014 4:59:35 PM
*/
String value();
}
第三步:通过静态常量建立数据库中的功能ID与执行方法的一对一关系
?
public class FuncConstants {
/**
* 系统管理-角色管理-增加角色
*/
public final static String Xtgl_Jsgl_AddJs = "4399d98bb0d84114acb5693081e83bc9";
/**
* 系统管理 - 部门管理- 部门列表
*/
public final static String Xtgl_Bmgl_BmList = "dbc4bf80f8b6418788b79de204d37932";
}
第四步:在SpringMVC拦截器中验证权限
/**
@date Dec 12, 2013 4:20:04 PM
*/
public class FreeMarkerViewInterceptor extends HandlerInterceptorAdapter {
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView view) throws Exception {
String contextPath = request.getContextPath();
if (view != null) {
request.setAttribute("base", contextPath);
}
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//处理Permission Annotation,实现方法级权限控制
HandlerMethod method = (HandlerMethod)handler;
Permission permission = method.getMethodAnnotation(Permission.class);
//如果为空在表示该方法不需要进行权限验证
if (permission == null) {
return true;
}
//验证是否具有权限
if (!WebUtil.hasPower(request, permission.value())) {
response.sendRedirect(request.getContextPath()+"/business/nopermission.html");
return false;
}
return true;
//注意此处必须返回true,否则请求将停止
//return true;
}
}
至此,基于按钮、方法验证的细粒度权限体系完成!
可以试试用shiro进行控制
你需要 spring security 或者 shiro
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}