SpringMVC自定义注解并自定义解析器HandlerMethodArgumentResolver

1、创建保持常量的类Constants:

package com.loan.fore;

public class Constants {
	public static final String CURRENT_USER = "user";
	public static final String IsShow = "IsShow";
}

2、自定义注解CurrentUser.java:


package com.loan.fore.bind.annotation;


import java.lang.annotation.*;

import com.loan.fore.Constants;

/** 
* @ClassName: CurrentUser 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author jiayq
* @date 2016年9月28日 下午5:05:25 
*  
*/
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CurrentUser {

    /**
     * 当前用户在request中的名字
     *
     * @return
     */
    String value() default Constants.CURRENT_USER;

}


3、可通过拦截器或者过滤器对注解(Constants中的常量)赋值:

执行顺序:过滤器-->拦截器-->解析器

过滤器与拦截器的区别见:http://blog.csdn.net/dreamer_8399/article/details/76615293

个人觉得在此处的使用上,拦截器是优于过滤器:原因如下:

1>拦截器可以对spring注入的service直接调用

2>个人测试发现,如果信息被修改后,filter注解不能实时更新。

1)拦截器:

package com.loan.fore.shiro.filter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.loan.fore.Constants;
import com.loan.fore.bind.method.IsShowDTO;
import com.loan.fore.entity.UsersIntended;
import com.loan.fore.util.ReturnEntityUtils;
import com.loan.fore.util.ThreeDESUtil;
import com.loan.security.pojo.PidUsernameDTO;
import com.loan.security.service.ResourceService;

public class LoanInterceptor implements HandlerInterceptor{
	@Value("${isProduct}")
	private String isProduct;
	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object o, Exception e)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object o, ModelAndView model)
			throws Exception {
		Map map2 = new HashMap<>();
		if(req.getAttribute("returnMap")!=null){
			Map map = (Map) req.getAttribute("returnMap");
			//如果是生产模式的话,对返回map进行加密
			if(isProduct.equals("true")){
				try {
					String resCiphertext = ThreeDESUtil.encryptThreeDESECB(JSON.toJSONString(map), ThreeDESUtil.KEY);
					map2.put("dec", resCiphertext);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				resp.getWriter().write(JSON.toJSONString(ReturnEntityUtils.SUCCESS_RETURN.put(map2)));
			}
			//其他情况直接返回map,方便开发人员调试
			else{
				resp.getWriter().write(JSON.toJSONString(ReturnEntityUtils.SUCCESS_RETURN.put(map)));
			}
			}
		else{
			map2.put("dec", "");
			resp.getWriter().write(JSON.toJSONString(ReturnEntityUtils.SUCCESS_RETURN.put(map2)));
		}
		
	}
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception {
		System.out.println("preHandle");
		// 获得在下面代码中要用的request,response,session对象
		String ciphertext = "";
		if (req.getParameter("ciphertext") != null) {
			ciphertext = req.getParameter("ciphertext").toString();
		}
		String res = ThreeDESUtil.decryptThreeDESECB(ciphertext, ThreeDESUtil.KEY);
		resp.setContentType("application/json;charset=utf-8");
		String path = req.getRequestURI();
		//把解密数据setAttribute
		req.setAttribute("ciphertext", res);
		//如果是生产模式的话,对请求进行拦截
		if(isProduct.equals("true")){
			String xEquipment = req.getHeader("X-Equipment");
			if (xEquipment != null) {
				if (xEquipment.indexOf("/约定标识") > 0) {
					getCurrentUser(req);
					return true;
				} else {
					resp.sendRedirect("/creditAPP/errorRequest");
					return false;
				}
			} else {
				resp.sendRedirect("/creditAPP/errorRequest");
				return false;
			}
		}
		//如果是开发、test模式的话,不进行拦截,方便开发人员进行测试
		else{
			getCurrentUser(req);
			return true;	
		}
	}
		/**
		 * 描述:
获取用户当前用户 * HTTP Method: GET
* 接口地址: * @param req
* "remarks": "No remarks"
* "returnReason": "OK" 成功
* "returnStatus": 200 返回成功
* "returnTotal": returnInformation的个数
* "returnInformation":
* {
* }
* Author:贾钰琴
* Date: 2017年8月14日 下午4:35:15 */ private void getCurrentUser(HttpServletRequest req){ HttpSession session = req.getSession(); UsersIntended user=(UsersIntended)session.getAttribute("currentUser"); req.setAttribute(Constants.CURRENT_USER,user); } }
dispatcher-servlet.xml配置:
    
		


        
        
            
            
            
            
        
    


2)过滤器:

package com.loan.fore.shiro.filter;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.PathMatchingFilter;

import com.loan.fore.Constants;
import com.loan.fore.entity.UsersIntended;
import com.loan.fore.service.UsersIntendedService;
/** 
* @ClassName: SysUserFilter 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author jiayq
* @date 2014年12月5日 下午1:25:00 
*  
*/
public class SysUserFilter extends PathMatchingFilter {
	@Resource
	private UsersIntendedService usersIntendedService;
	@Override
	protected boolean onPreHandle(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		HttpServletRequest servletRequest = (HttpServletRequest) request;
		HttpSession session = servletRequest.getSession();
		UsersIntended user=(UsersIntended)session.getAttribute("currentUser");
		request.setAttribute(Constants.CURRENT_USER,user);
		return true;
	}
}

web.xml中进行配置:
  
    sysUserFilter
    com.loan.fore.shiro.filter.SysUserFilter
  
  
    sysUserFilter
    /*
  



4、解析器CurrentUserMethodArgumentResolver.java


package com.loan.fore.bind.method;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.loan.fore.bind.annotation.CurrentUser;

/** 
* @ClassName: CurrentUserMethodArgumentResolver 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author jiayq
* @date 2016年9月28日 下午5:06:35 
*  
*/
public class CurrentUserMethodArgumentResolver implements
		HandlerMethodArgumentResolver {

	public CurrentUserMethodArgumentResolver() {
	}

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		if (parameter.hasParameterAnnotation(CurrentUser.class)) {
			return true;
		}
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		CurrentUser currentUserAnnotation = parameter
				.getParameterAnnotation(CurrentUser.class);
		return webRequest.getAttribute(currentUserAnnotation.value(),
				NativeWebRequest.SCOPE_REQUEST);
	}
}

5、dispacher-servlet.xml配置解析器

    
		
			
		
	


6、Controller,注解的使用

@RequestMapping("/test")
public void index(HttpServletRequest req,HttpServletResponse rep,@CurrentUser UsersIntended user) throws Exception{
	System.out.println(user);
}





你可能感兴趣的:(框架)