自定义注解

最近写了一个自定义注解的示例:验证是否需要登陆

自定义注解:

package com.pms.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 登录验证注解
 * 该注解可以标记Controller 或 Controller 中的方法.
 * 如果Controller 有该标记,那么这个Controller下面所有的方法都会被过滤器
 * 进行验证
 * 如果Controller 没有有该标记,但Controller中的某个方法拥有该标记
 * 那么这个方法将被过滤器验证(其他没有被标记的不会被验证)
 *
 * 特别注意,如果一个Controller 被标记RequireLogin 需要验证
 * 但是其中某些方法不想被验证.请参见NoRequireLogin标记
 *
 * 
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)//定义该Annotation被保留的时间
@Target({ElementType.METHOD, ElementType.TYPE})//该注解修饰类中的方法
@Inherited
public @interface RequireLogin{
 
}
package com.pms.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 不需要登录验证的方法注解注解
 * 该注解在Controller 标记了 RequireLogin 特性时
 * 某个方法不需要验证登录,那么为该方法标记该注解
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)//
@Target(ElementType.METHOD)//该注解修饰类中的方法
@Inherited
public @interface NoRequireLogin{

}

通过拦截器使用:

package com.pms.inteceptor;

import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.pms.annotation.NoRequireLogin;
import com.pms.annotation.RequireLogin;
import com.pms.commons.pojo.ResponseEntity;
import com.pms.commons.pojo.ResponseVoConstant;
import com.pms.exception.DealException;
import com.pms.utils.MessageUtil;

import net.sf.json.JSONObject;
/** 权限拦截器
 * @author 
 *
 */
public class AuthInteceptor extends HandlerInterceptorAdapter implements DealException{
 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	
    	if (handler instanceof HandlerMethod) {
            HandlerMethod myHandlerMethod = (HandlerMethod) handler;
            Object bean = myHandlerMethod.getBean();
            Method method= myHandlerMethod.getMethod();
            Annotation classAnnotation = bean.getClass().getAnnotation(RequireLogin.class);//类上有该标记
            Annotation methodAnnotation=method.getAnnotation(RequireLogin.class);//方法上有该标记
            Annotation methodNologinAnnotation=method.getAnnotation(NoRequireLogin.class);//方法上有该标记的
            if((classAnnotation!=null&&methodNologinAnnotation==null)
                    ||(classAnnotation==null&&methodAnnotation!=null))
            {
            	//System.out.println("begin to 拦截器");
            	//System.out.println("username值:"+request.getSession().getAttribute("username"));
                boolean isLogin = (request.getSession().getAttribute("username")!=null);
                if(isLogin)
                    return true;
                else{//未登录
                	
                    PrintWriter out=response.getWriter();
    	            out.write(JSONObject.fromObject(ResponseEntity.status(ResponseVoConstant.INVALIDLOGINSTATUS).data(null).errorMessage(MessageUtil.getMessageValue("REGAIN_LOGIN"))).toString());
    	            out.close();
    	            return false;
                     
                }//IF LOGIN END
            }//if Annotation end
        }
        return true;
    }

	@Override
	public ResponseEntity exception(HttpServletRequest request, Exception e) {
		 return ResponseEntity.status(ResponseVoConstant.SERVEREXCEPTION).
			data(null).errorMessage(MessageUtil.getMessageValue("ERROR_MESSAGE"));
	}
}

这样简单的自定义注解判断是否验证就做完了,只需要再你想要验证的类上加上注解就行了

示例:

不需要验证的:

/**
	 * 登陆
	 * @param user
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getUser")
	@ResponseBody
	@NoRequireLogin
	public ResponseEntity getUser(@RequestBody User user,HttpSession session) throws Exception{
		
		List<User> UserList = null;
		try {
			UserList = loginService.checkLogin(user);
		} catch (Exception e) {
			
			 return ResponseEntity.status(ResponseVoConstant.SERVEREXCEPTION).
				    	data(null).errorMessage(MessageUtil.getMessageValue("ERROR_MESSAGE"));
		}
		if(UserList.isEmpty()){
			
			return  ResponseEntity.status(ResponseVoConstant.BADREQUEST).
					data(null).errorMessage(MessageUtil.getMessageValue("NOT_EXISTS_USER"));
		}
		User dbUser=UserList.get(0);
		if(!dbUser.getStaffPass().equals(user.getStaffPass())){
			
		   	return ResponseEntity.status(ResponseVoConstant.BADREQUEST).
		   			data(null).errorMessage(MessageUtil.getMessageValue("ERROR_PASSWORD"));
		}
		
		session.setAttribute("username", dbUser.getStaffLoginName());
		session.setAttribute("userId", dbUser.getId());
		session.setAttribute("staffCharactor", dbUser.getStaffCharactor());
		session.setAttribute("user", dbUser);
		    dbUser.setStaffPass(null);
		    JSONObject.fromObject(dbUser);
		    return ResponseEntity.status(ResponseVoConstant.OK).
			    	data(dbUser).errorMessage(MessageUtil.getMessageValue("LOGIN_SUCCESS"));
	}

需要验证的:

/**
	 * 保存客户信息之后返回保存的实体类
	 * @param customer
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("saveCustomer")
	@ResponseBody
	@RequireLogin
	public ResponseEntity saveCustomer(@RequestBody Customer customer, HttpSession session) throws Exception{
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-DD hh:mm:ss");
		customer.setCreationTime(sdf.parse(sdf.format(date
				)));
		customer.setModifiedTime(sdf.parse(sdf.format(date)));
		customer.setCreationUserId(Integer.parseInt(session.getAttribute("userId").toString()));
		customer.setModifiedUserId(Integer.parseInt(session.getAttribute("userId").toString()));
		List<Customer> cust =null; 
		Customer  Retcustomer=null;
		try{
			cust=	customerService.findByCustomerName(customer.getCustomerName());
		if(cust.size()!=0){
			return ResponseEntity.status(ResponseVoConstant.BADREQUEST).
			    	data(null).errorMessage(MessageUtil.getMessageValue("CUSTOMER_HAS_EXIST"));
		}
		customerService.save(customer);
		Retcustomer= customerService.findByCustomerName(customer.getCustomerName()).get(0);
		
		}catch (Exception e) {
			
		return ResponseEntity.status(ResponseVoConstant.BADREQUEST).
			    	data(null).errorMessage(MessageUtil.getMessageValue("SAVE_FAIL"));
		}
		return ResponseEntity.status(ResponseVoConstant.OK).
			    	data(Retcustomer).errorMessage(MessageUtil.getMessageValue("SAVE_SUCCESS"));
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值