当用户无权限访问某个java方法时,可以通过自定义注解进行控制访问权限
1、定义注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface Login {
ResultTypeEnum value() default ResultTypeEnum.json;
}
其中 ResultTypeEnum 为枚举类型,来相应用户请求参数的类型
/**
* 枚举类型 返回结果枚举
* 2014-10-15
*
*/
public enum ResultTypeEnum {
page,
json
}
2、编写拦截类,在spring管理进行请求方法的拦截,对于有写Login注解的方法进行判断,如果未登陆,则进行返回,否则用户登录验证通过
public class LoginAnnotationInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(handler instanceof HandlerMethod){
HandlerMethod handler2 = (HandlerMethod) handler;
Login login = handler2.getMethodAnnotation(Login.class);
if (null != login) {// 没有注解声明权限,放行
/**从header中区别用户是否登录过**/
String userId=request.getHeader(CommonStaticConstant.USER_ID);
if (null == userId) {
// 依据请求类别返回不同数据
if (login.value() == ResultTypeEnum.page) {
//跳转到传统页面的登录
//request.getRequestDispatcher("/login.jsp?oprst=false&opmsg=请<strong><strong>登录</strong></strong>!").forward(request, response);
} else {
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=UTF-8");
OutputStream out = response.getOutputStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(out,"utf-8"));
//返回json格式的提示
pw.println("{\"code\":\""+HttpStatus.NOT_ACCEPTABLE.value()+"\",\"msg\":\"请先登录\"}");
pw.flush();
pw.close();
}
return false;
}
}
}
return true;
}
}
3、在spring配置文件application.xml中进行配置
<!-- 添加监听,对添加了注解需要监听的方法进行监听 未登陆的操作需要返回至登陆界面 add by atao 2014-10-16 -->
<mvc:interceptors>
<bean class="com.yjh.mobile.listener.CommonInterceptor" />
<bean class="com.yjh.mobile.listener.LoginAnnotationInterceptor" />
</mvc:interceptors>
4、在需要验证登陆的方法上架上注解验证效果
/**
* 通过商品或者用户条件查询当前用户下已经收藏过得所有商品
* @param id
* @return CollectGoods
* 2014-10-11
*/
@Login(ResultTypeEnum.json)
@RequestMapping(value = "/list",method = RequestMethod.GET)
public List<CollectGoods> getCollectGoodsList(@RequestParam(required = false) Integer rowNum
,@RequestHeader(value = CommonStaticConstant.USER_ID, required = true) String userId)
{
Map<String, Object> param = new HashMap<String, Object>();
param.put("user_id", userId);
param.put("count", count);
return collectGoodsMapper.list(param);
}