功能是,验证用户是否用controller方法上注解内的权限码,没有则不能进入方法
注解定义代码:
package com.jd.las.goods.attribute.permission;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 权限码定义
* @author yanghao
* @see com.jd.common.struts.interceptor.HrmPrivilege
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LasPrivilege {
/**
* 权限码。可以用“,”分隔多个。表示都可以访问。
*
* @return
*/
public String value();
}
拦截器代码:
package com.jd.las.goods.attribute.web.springmvc.interceptor;
import com.jd.las.goods.attribute.permission.LasPrivilege;
import com.jd.las.goods.attribute.permission.ws.client.PermissionClient;
import com.jd.las.goods.attribute.web.action.SingleLoginUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 拦截方法执行时的注解。以确定是否有权限执行。 <br/>
*
* port from com.jd.common.struts.interceptor.HrmDotnetPrivilegeInterceptor,
* remove dependency with struts.
*
* @author dbyanghao
*/
public class LasPrivilegeInterceptor extends HandlerInterceptorAdapter {
private SingleLoginUtil singleLoginUtil;
//调用权限系统获取菜单service注入
@Resource(name = "permissionClientImpl")
private PermissionClient permissionClient;
@Override
public final boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception{
String username = getUsername(request);
LasPrivilege annotation = null;
if(handler instanceof HandlerMethod){
annotation = ((HandlerMethod) handler)
.getMethodAnnotation(LasPrivilege.class);
}else{
return true;
}
if (annotation != null) {
String code = annotation.value();// 资源需要的权限
if (StringUtils.isNotEmpty(code)) {
if (username == null
|| !permissionClient.judgeUserResource(username, code)) {
throw new Exception(
"没有足够权限!");
}
}
}
return true;
}
/**
* 取得用户名
*
* @return
*/
protected String getUsername(HttpServletRequest request) {
String username = singleLoginUtil.getUserInfo(request);
return username;
}
public SingleLoginUtil getSingleLoginUtil() {
return singleLoginUtil;
}
public void setSingleLoginUtil(SingleLoginUtil singleLoginUtil) {
this.singleLoginUtil = singleLoginUtil;
}
}
spring拦截器配置
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<ref bean="_LasPrivilegeInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<bean id="_LasPrivilegeInterceptor"
class="com.jd.las.goods.attribute.web.springmvc.interceptor.LasPrivilegeInterceptor">
<property name="singleLoginUtil" ref="singleLoginUtil" />
</bean>
controller上的方法
@LasPrivilege("GOODS_ATTRIBUTE_MANAGER")
@RequestMapping(value = "/initpage")
public String initPage() {
logger.info("GoodsAttributeManagerController的initPage方法执行");
return "goodsattributemanager/goodsattributemanager-list";
}