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. 微信小程序开发(二)----- 云开发

    1.概念 微信小程序的云开发是腾讯云与微信团队深度合作推出的一个全新的小程序的解决方案,它提供了云函数.云数据库与云存储这三大基础能力支持,随着云开发的出现,小程序的开发者可以将服务端的部署和运营的环 ...

  2. [Python3] 027 常用模块 time

    目录 time 1. 时间戳 2. UTC 时间 3. 夏令时 4. 时间元组 5. 举例 5.1 例子1 例子2 例子3 例子4 例子5 例子6 例子7 time 1. 时间戳 一个时间表示,根据不 ...

  3. Spring(一)--Spring简介

    Spring简介 1. Spring的特点 Spring (春天,绿色)  容器 01.Java EE开发者的春天,大大简化了代码量 02.使用IOC来降低主业务之间的耦合度 03.使用AOP来降低主 ...

  4. Java -cp命令的使用

    服务器跑程序,用到了一些Linux命令,做个简单笔记. Linux(Mac)下 java -cp .:jar包路径 主类的全限定名称     全限定名有绝对路径的意思,比如一个文件file的存放路径, ...

  5. 03: redis高级

    1.1 布隆过滤器 1.布隆过滤器是什么?(判断某个key一定不存在) 1. 本质上布隆过滤器是一种数据结构,比较巧妙的概率型数据结构 2. 特点是高效地插入和查询,可以用来告诉你 “某样东西一定不存 ...

  6. python基础预习小结

    一.执行python程序的两种方式 1.1 交互式 在终端内输入python3,然后输入python代码 1.2 命令式 在终端内输入python3文本文件路径 二.执行python的两种IDE 2. ...

  7. CTP报单参数详解

    交易所代码 产品类型 业务类型 价格类型 指令类型 价格类型 OrderPriceType 有效期类型 TimeCondition 成交量类型 VolumeCondition 备注 CZCE 郑商所 ...

  8. 10分钟,让你彻底明白Promise原理

    什么是Promise?本代码用定外卖来举例子,让你明白. // 定外卖就是一个Promise,Promist的意思就是承诺// 我们定完外卖,饭不会立即到我们手中// 这时候我们和商家就要达成一个承诺 ...

  9. sqlite3中 timestamp使用

    timestamp使用 一. timestamp两种属性:自动初始化: 此行为只在第一次写入数据时,怎么把时间设为当前时间. (DEFAULT CURRENT_TIMESTAMP)自动更新: 此行为在 ...

  10. Python3零基础入门学习视频+源码+课件+习题-小甲鱼

    目录 1. 介绍 2. 目录 3. 下载地址 1. 介绍 适用人群 完全零基础入门,不需要任何前置知识. 课程概述 本系列教程面向零基础的同学,是一个深入浅出,通俗易懂的Python3视频教程. 前半 ...