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<String, Object> map2 = new HashMap<>();
		if(req.getAttribute("returnMap")!=null){
			Map<String, Object> map = (Map<String, Object>) 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;	
		}
	}
		/**
		 * <b>描述:</b><br>获取用户当前用户
		 * <b>HTTP Method:</b> GET <br>
		 * <b>接口地址:</b>
	     * @param req <br>
		 * "remarks": "No remarks" <br>
		 * "returnReason": "OK" 成功 <br>
		 * "returnStatus": 200 返回成功 <br>
		 * "returnTotal":  returnInformation的个数 <br>
		 * "returnInformation": <br>
		 *             { <br>
		 *             } <br>
		 *  <b>Author:</b>贾钰琴 <br>
		 * <b>Date:</b> 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配置:
    <mvc:interceptors>
		<!--所有Url均拦截 -->
<!-- 	<bean class="com.loan.fore.shiro.filter.LoanInterceptor"/> -->
<!--         对特定的url拦截 -->
        <mvc:interceptor>
        <!-- /**的意思是所有文件夹及里面的子文件夹
			/*是所有文件夹,不含子文件夹
            /是web项目的根目录 -->
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/static/*"/>
            <mvc:exclude-mapping path="/errorRequest"/>
            <bean class="com.loan.fore.shiro.filter.LoanInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>


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中进行配置:
  <filter>
    <filter-name>sysUserFilter</filter-name>
    <filter-class>com.loan.fore.shiro.filter.SysUserFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>sysUserFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>



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配置解析器

    <mvc:annotation-driven>
		<mvc:argument-resolvers>
			<bean class="com.loan.fore.bind.method.CurrentUserMethodArgumentResolver" />
		</mvc:argument-resolvers>
	</mvc:annotation-driven>


6、Controller,注解的使用

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





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值