1、spring自定义注解实现登陆拦截器

  原理:定义一个注解和一个拦截器,拦截器拦截所有方法请求,判断该方法有没有该注解。没有,放行;有,要进行验证。从而实现方法加注解就需要验证是否登陆。

2、自定义注解

package com.oy.filter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; // can be used to method
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface IsLogin { }

3、登陆拦截器

package com.oy.filter;
import java.text.MessageFormat; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import amberai.jweb.utils.UtilFunctions; public class LoginInterceptor extends HandlerInterceptorAdapter { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception { Cookie[] cs = request.getCookies();
if (cs != null && cs.length > 0 ) {
for (Cookie c : cs) {
UtilFunctions.log.info("==== LoginInterceptor#preHandle, cookie.key:{}, cookie.value:{} ====", c.getName(), c.getValue());
}
} request.setAttribute("resourceBundle", Utils.getResourceBundle(request)); String sessionId = Utils.getSessionId(request);
Integer uid = Utils.getUserId(request);
String controllerName = Utils.getClassName(handler);
String methodName = Utils.getMethodName(handler);
String handlerTypeName = handler.getClass().getName();
// String language = Utils.getLanguage(request); // if url?l=zh-cn1, then language = en-us
// if url?l=zh-cn1, then language = zh-cn1.
String language = request.getParameter("l");
if (language == null) {
language = Utils.getLanguageByCookie(request);
} String logMsg = MessageFormat.format("sessionId:{0}, uid:{1}, controllerName:{2}, methodName:{3}, handlerTypeName:{4}, language:{5}",
sessionId, uid, controllerName, methodName, handlerTypeName, language);
UtilFunctions.log.info("LoginInterceptor#preHandle LoginInterceptor work, " + logMsg); long begin = System.currentTimeMillis(); // target of request is method of controller
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Object object = handlerMethod.getMethodAnnotation(IsLogin.class); if (object == null) { // method without @IsLogin annotation
long time = System.currentTimeMillis() - begin;
UtilFunctions.log.info("LoginInterceptor#preHandle over, method[{}] without annotation, takes time:{} ms, " + logMsg, methodName, time);
return true;
} else { // method with @IsLogin annotation
if (uid == null) {
// visitor
response.setStatus(401);
long time = System.currentTimeMillis() - begin;
UtilFunctions.log.info("LoginInterceptor#preHandle over, visitor request intercepted, takes time:{} ms, " + logMsg, time);
return false;
} // user
request.setAttribute("uid", uid);
}
} long time = System.currentTimeMillis() - begin;
UtilFunctions.log.info("LoginInterceptor#preHandle over, user request ok, takes time:{} ms, " + logMsg, time); return true;
} }

  

  spring配置文件中注册拦截器

<mvc:interceptors>
<bean class="com.oy.filter.LoginInterceptor" />
</mvc:interceptors>

4、Utils类

package com.oy.filter;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest; import org.springframework.web.method.HandlerMethod; import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils; import amberai.jweb.utils.Config;
import amberai.jweb.utils.RedisAccess;
import amberai.jweb.utils.UtilFunctions;
import redis.clients.jedis.Jedis; public class Utils { public static String getSessionId(HttpServletRequest request) {
String sessionId = null; if (request == null) {
return sessionId;
} Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length == 0) {
return sessionId;
} for (Cookie cookie : cookies) {
if ("PHPSESSID".equalsIgnoreCase(cookie.getName())) {
sessionId = cookie.getValue();
}
} return sessionId;
} public static Integer getUserId(String sessionId) {
Integer uid = null; if (null == sessionId) {
return uid;
} JSONObject userInfo = Utils.getUserInfoFromRedis(sessionId);
if (null == userInfo || userInfo.getIntValue("userId") <= 0) {
return uid;
}
uid = userInfo.getIntValue("userId");
return uid;
} public static Integer getUserId(HttpServletRequest request) {
Integer uid = null; if (null == request) {
return uid;
} String sessionId = getSessionId(request);
if (sessionId == null) {
return uid;
} JSONObject userInfo = Utils.getUserInfoFromRedis(sessionId);
if (null == userInfo || userInfo.getIntValue("userId") <= 0) {
return uid;
}
uid = userInfo.getIntValue("userId");
return uid;
} public static JSONObject getUserInfoFromRedis(String sessionId) {
if (sessionId == null) {
return null;
} UtilFunctions.log.debug("checkLogin, sessionId:{}", sessionId);
Jedis redisClient = null;
try {
redisClient = RedisAccess.getRedisClient(); String userInfo = redisClient.get("sess_" + sessionId);
UtilFunctions.log.debug("checkLogin, userInfo:{}", userInfo);
if (null == userInfo) {
return null;
}
JSONObject jsonObj = null;
try {
jsonObj = JSONObject.parseObject(userInfo);
} catch (JSONException e) {
String errMsg = MessageFormat.format("can not cast to JSONObject. sessionId:{0}, userInfo:{1}",
sessionId, userInfo);
UtilFunctions.log.info(errMsg);
UtilFunctions.reportError(errMsg, e);
}
return jsonObj;
} finally {
if (null != redisClient) {
redisClient.close();
}
}
} public static String getMethodName(Object handler) {
if (null == handler) {
return "";
} if (HandlerMethod.class.equals(handler.getClass())) {
HandlerMethod method = (HandlerMethod) handler;
return method.getMethod().getName();
} return "";
} public static String getClassName(Object handler) {
if (null == handler) {
return "";
} if (HandlerMethod.class.equals(handler.getClass())) {
// get controller
HandlerMethod method = (HandlerMethod) handler;
Object controller = method.getBean(); String className = controller.getClass().getName();
int idx = className.lastIndexOf("."); if (idx >= 0 && (idx + 1) < className.length()) {
return className.substring(idx + 1);
}
return className;
} return "";
} public static String getRemoteIp(HttpServletRequest request) {
if (null == request) {
return "";
} String ip = request.getHeader("x-forwarded-for");
if (StringUtils.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
} if (StringUtils.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
} if (StringUtils.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
} return ip; } public static String getLanguage(HttpServletRequest request) {
String language = "";
if (request == null) return language; // priority: url?l=en-us > Cookie:language=zh-cn
language = request.getParameter("l");
if (language == null || Config.LANGUAGECONFIG.get(language.toLowerCase()) == null) {
language = Utils.getLanguageByCookie(request);
} if (language == null || Config.LANGUAGECONFIG.get(language.toLowerCase()) == null) {
language = "en-us"; // default "en-us"
} return language;
} public static String getLanguageByCookie(HttpServletRequest request) {
String language = "";
if (request == null) return language; Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length == 0) {
return language;
} for (Cookie cookie : cookies) {
if ("language".equalsIgnoreCase(cookie.getName())) {
language = cookie.getValue();
}
} return language;
} public static ResourceBundle getResourceBundle(HttpServletRequest request) {
String language = Utils.getLanguage(request);
String[] languages = language.split("-");
Locale locale = null;
if (languages.length >= 2) {
locale = new Locale(language.split("-")[0], language.split("-")[1]);
} else if (languages.length == 1) {
locale = new Locale(language.split("-")[0], "ES");
}
return ResourceBundle.getBundle("i18n/MessgesBundle", locale);
} public static void setSessionAttrToRedis(String sessionId, String jsonStr) {
Jedis redisClient = null;
try {
redisClient = RedisAccess.getRedisClient();
redisClient.set("sess_" + sessionId, jsonStr);
redisClient.expire("sess_" + sessionId, 3600);
} finally {
if (null != redisClient) {
redisClient.close();
}
}
}
}

5、使用@IsLogin

@IsLogin
@RequestMapping(value = "/xxx/xxx", method = RequestMethod.POST)
@ResponseBody
public JSONObject setPayPassword(HttpServletRequest request,
@RequestParam(value = "xxx", required = true) String xxx,
@RequestParam(value = "xxx", required = true) String xxx) {   Integer userId = (Integer) request.getAttribute("uid");
  ResourceBundle resourceBundle = (ResourceBundle) request.getAttribute("resourceBundle");
  ...
}

spring自定义注解实现登陆拦截器的更多相关文章

  1. Spring实现自定义注解并且配置拦截器进行拦截

    有时候我们会自定义注解,并且需要配置拦截器对请求方法含有该自定义注解的方法进行拦截操作 自定义注解类 NeedToken.java import java.lang.annotation.Docume ...

  2. JAVAEE——struts2_04:自定义拦截器、struts2标签、登陆功能和校验登陆拦截器的实现

    一.自定义拦截器 1.架构 2.拦截器创建 //拦截器:第一种创建方式 //拦截器生命周期:随项目的启动而创建,随项目关闭而销毁 public class MyInterceptor implemen ...

  3. Spring Boot使用过滤器和拦截器分别实现REST接口简易安全认证

    本文通过一个简易安全认证示例的开发实践,理解过滤器和拦截器的工作原理. 很多文章都将过滤器(Filter).拦截器(Interceptor)和监听器(Listener)这三者和Spring关联起来讲解 ...

  4. [转载]开发 Spring 自定义视图和视图解析器

    原文出处 http://www.ibm.com/developerworks/cn/java/j-lo-springview/ 概述 Spring 3.0 默认包含了多种视图和视图解析器,比如 JSP ...

  5. 通过spring抽象路由数据源+MyBatis拦截器实现数据库自动读写分离

    前言 之前使用的读写分离的方案是在mybatis中配置两个数据源,然后生成两个不同的SqlSessionTemplate然后手动去识别执行sql语句是操作主库还是从库.如下图所示: 好处是,你可以人为 ...

  6. 【Java EE 学习 70 上】【数据采集系统第二天】【数据加密处理】【登陆验证】【登陆拦截器】【新建调查】【查询调查】

    一.数据加密处理 这里使用MD5加密处理,使用java中自带加密工具类MessageDigest. 该类有一个方法digest,该方法输入参数是一个字符串返回值是一个长度为16的字节数组.最关键的是需 ...

  7. Spring AOP 源码分析 - 拦截器链的执行过程

    1.简介 本篇文章是 AOP 源码分析系列文章的最后一篇文章,在前面的两篇文章中,我分别介绍了 Spring AOP 是如何为目标 bean 筛选合适的通知器,以及如何创建代理对象的过程.现在我们的得 ...

  8. Spring AOP深入理解之拦截器调用

    Spring AOP深入理解之拦截器调用 Spring AOP代理对象生成回想 上一篇博客中:深入理解Spring AOP之二代理对象生成介绍了Spring代理对象是怎样生成的,当中重点介绍了JDK动 ...

  9. Spring MVC基础知识整理➣拦截器和自定义注解

    概述 Spring MVC中通过注解来对方法或者类进行动态的说明或者标注,类似于配置标识文件的属性信息.当标注的类或者方式被使用时候,通过提取注解信息来达到对类的动态处理.在 MVC中,我们常用的注解 ...

随机推荐

  1. illustrator 偏方

    视图 边角构件  - - 这个是显示边角弧度的

  2. Buffer对象与JSON对象相互转换

    > buffer=new Buffer('换汤不换药');<Buffer e6 88 91 e7 88 b1 e4 bd a0 ef bc 8c e7 89 a9 e7 90 86> ...

  3. PMP项目正常估算时间

    最佳时间段+正常时间段*+最差时间段)/=正常估算时间. 项目经理小李对某活动工期进行估算时,发现人员的熟练程度和设备供应是否及时对工期至关重要.如果形成最有利组合时,预计17天可以完成:如果形成最不 ...

  4. HDU 1263 水果 (STL map)

    水果 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submissi ...

  5. HDU-4332-Constructing Chimney

    题目描述 用\(1*1*2\)的砖头摆出如图所示的烟囱,可以横着摆也可以竖着摆,求摆出\(n\)层高的烟囱会有多少种不同的方案. Input 一共有\(T\)组数据. 每组数据包含一个\(n(1 \l ...

  6. PropertyUtilsBean 将bean转成map

    public static Map<String,String> beanToMap(Object bean) { Map<String,String> params =Map ...

  7. sql修改表名字段名

    修改字段: ALTER TABLE user_info CHANGE NAME name VARCHAR(10); 修改表名alter TABLE user_role RENAME user_info ...

  8. Vue.nextTick 的原理和用途

    转载自https://segmentfault.com/a/1190000012861862 概览 官方文档说明: 用法: 在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法 ...

  9. iptables - IP包过滤器管理

    总览 iptables -ADC 指定链的规则 [-A 添加 -D 删除 -C 修改] iptables - RI iptables -D chain rule num[option] iptable ...

  10. 问题:关于2.3 jmu-Java-02基本语法-03-身份证排序 (9 分)

    输出未能排序     import java.util.Scanner;     import java.util.Arrays;     public class Main {         pu ...