java web项目中注解控制登录

当用户无权限访问某个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);
	}
	


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值