coding++:java-自定义签名+拦截器
本次案例工具为:SpringBoot <version>1.5.19.RELEASE</version>
Code:

1、annotations
package com.mlq.annotations; import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; @Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface ActionAuth {
enum Type {
DEMO, TEST
} /**
* 操作类型
*
* @return
*/
Type value() default Type.DEMO; /**
* 操作名称
*
* @return
*/
String name() default ""; /**
* 操作Code
*
* @return
*/
String code() default ""; }
ActionAuth
2、config
package com.mlq.config; import com.mlq.interceptors.AppInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /**
* @Description: 拦截器config
*/
@Configuration
public class WebConfigurerConfig extends WebMvcConfigurerAdapter { @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AppInterceptor()).addPathPatterns("/**");
} }
WebConfigurerConfig
3、controller
package com.mlq.controller; import com.mlq.annotations.ActionAuth;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/signature/")
public class SignatureTest { @RequestMapping("getSignature")
public Object getSignature() {
return "验证通过";
} @ActionAuth(value = ActionAuth.Type.DEMO, name = "ok", code = "ok")
@RequestMapping("ok")
public Object ok() {
return "验证通过";
} }
SignatureTest
4、exception
package com.mlq.exception;
import com.mlq.tools.ErrorPrintUtils;
public abstract class AbstractException extends RuntimeException {
private static final long serialVersionUID = -5992753399315247713L;
private String errorCode;
private String errorMsg;
private String stackTraceMsg;
private String level;
private String messageID;
private boolean sendMsg = true;
public AbstractException(String code, String message, String... level) {
super(code + "|" + message);
this.handleExceptionMessage(code, message, code + "|" + message);
}
public AbstractException(String code, String message, Throwable th) {
super(code + "|" + message, th);
this.handleExceptionMessage(code, message, ErrorPrintUtils.printStackTrace(th));
}
public final void handleExceptionMessage(String code, String message, String stackTraceMsg) {
this.errorCode = code;
this.errorMsg = message;
this.stackTraceMsg = stackTraceMsg;
}
public AbstractException(Throwable cause) {
super(cause);
AbstractException.ErrorDesc errorDesc = this.getErrorDesc(cause);
if (errorDesc != null) {
this.errorCode = errorDesc.errorCode;
this.errorMsg = errorDesc.errorMsg;
}
}
public AbstractException(String message) {
super(message);
}
public abstract AbstractException.ErrorDesc getErrorDesc(Throwable var1);
public String getErrorCode() {
return this.errorCode;
}
public String getErrorMsg() {
return this.errorMsg;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getStackTraceMsg() {
return this.stackTraceMsg;
}
public void setStackTraceMsg(String stackTraceMsg) {
this.stackTraceMsg = stackTraceMsg;
}
public String getLevel() {
return this.level;
}
public void setLevel(String level) {
this.level = level;
}
public String getMessageID() {
return this.messageID;
}
public void setMessageID(String messageID) {
this.messageID = messageID;
}
public boolean isSendMsg() {
return this.sendMsg;
}
public void setSendMsg(boolean sendMsg) {
this.sendMsg = sendMsg;
}
public static class ErrorDesc {
public String errorCode;
public String errorMsg;
public ErrorDesc(String errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
}
}
AbstractException
package com.mlq.exception;
public class ControllerException extends AbstractException {
private static final long serialVersionUID = 8307533385237791476L;
public ControllerException(String code, String message) {
super(code, message, new String[0]);
}
public ControllerException(String code, String message, Throwable th) {
super(code, message, th);
}
public AbstractException.ErrorDesc getErrorDesc(Throwable var1) {
return null;
}
}
ControllerException
package com.mlq.exception; /**
* JsonException
*/
public class JsonException extends ControllerException { private static final long serialVersionUID = -5605565877150120787L; public JsonException(String code, String message) {
super(code, message);
} public JsonException(String code, String message, Throwable th) {
super(code, message, th);
} }
JsonException
5、interceptors
package com.mlq.interceptors; import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.mlq.annotations.ActionAuth;
import com.mlq.exception.JsonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; /**
* 权限拦截器
*/
public class AppInterceptor implements HandlerInterceptor { /**
* 日志输出
*/
private static final Logger LOGGER = LoggerFactory.getLogger(AppInterceptor.class); @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //判断是否为处理程序方法
if (handler instanceof HandlerMethod) {
//强制类型转换
HandlerMethod method = (HandlerMethod) handler;
//获取方法指定签名
ActionAuth actionAuth = method.getMethodAnnotation(ActionAuth.class);
LOGGER.info("授权对象:actionAuth={}", actionAuth != null);
if (!ObjectUtils.isEmpty(actionAuth)) {
if (actionAuth.value().equals(ActionAuth.Type.DEMO)) {
return true;
} else {
throw new JsonException("500", "缺少权限配置");
}
} else {
throw new JsonException("500", "缺少权限配置:缺少签名配置");
}
/*
* 验证请求的方法上有没有固定签名设置...
* */
}
// Ajax 请求
if (checkAjaxRequest(request)) { }
return true;
} @Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
LOGGER.info("后期处理!!!");
} @Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
LOGGER.info("完成处理!!!");
} /**
* Ajax 请求
*
* @param request
* @return
*/
private boolean checkAjaxRequest(HttpServletRequest request) {
String requestType = request.getHeader("X-Requested-With");
// Ajax请求
if (!ObjectUtils.isEmpty(requestType) && "XMLHttpRequest".equals(requestType)) {
return true;
}
return false;
}
}
AppInterceptor
6、tools
package com.mlq.tools; import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter; public class ErrorPrintUtils { public ErrorPrintUtils() {
} public static String printStackTrace(Throwable exception) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
exception.printStackTrace(pw);
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException var8) {
;
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}
}
ErrorPrintUtils
提示:所有请求都会被拦截 要是不满足签名规范则会抛出异常
coding++:java-自定义签名+拦截器的更多相关文章
- Spring自定义一个拦截器类SomeInterceptor,实现HandlerInterceptor接口及其方法的实例
利用Spring的拦截器可以在处理器Controller方法执行前和后增加逻辑代码,了解拦截器中preHandle.postHandle和afterCompletion方法执行时机. 自定义一个拦截器 ...
- Mybatis自定义SQL拦截器
本博客介绍的是继承Mybatis提供的Interface接口,自定义拦截器,然后将项目中的sql拦截一下,打印到控制台. 先自定义一个拦截器 package com.muses.taoshop.com ...
- Java三大器之拦截器(Interceptor)的实现原理及代码示例
1,拦截器的概念 java里的拦截器是动态拦截Action调用的对象,它提供了一种机制可以使开发者在一个Action执行的前后执行一段代码,也可以在一个Action执行前阻止其执行,同时也提供了 ...
- 【java web】拦截器inteceptor
一.简介 java里的拦截器提供的是非系统级别的拦截,也就是说,就覆盖面来说,拦截器不如过滤器强大,但是更有针对性. Java中的拦截器是基于Java反射机制实现的,更准确的划分,应该是基于JDK实现 ...
- SpringMVC 自定义一个拦截器
自定义一个拦截器方法,实现HandlerInterceptor方法 public class FirstInterceptor implements HandlerInterceptor{ /** * ...
- java struts学习-拦截器
引言: Struts2拦截器,每个拦截器类只有一个对象实例,即采用单例模式,所有引用这个拦截器的Action都共享这一拦截器类的实例,因此,在拦截器中如果使用类变量,要注意同步问题. • ...
- Java结合SpringBoot拦截器实现简单的登录认证模块
Java结合SpringBoot拦截器实现简单的登录认证模块 之前在做项目时需要实现一个简单的登录认证的功能,就寻思着使用Spring Boot的拦截器来实现,在此记录一下我的整个实现过程,源码见文章 ...
- Dubbo自定义日志拦截器
前言 上一篇文章 Spring aop+自定义注解统一记录用户行为日志 记录了 web层中通过自定义注解配合Spring aop自动记录用户行为日志的过程.那么按照分布式架构中Dubbo服务层的调用过 ...
- springmvc自定义的拦截器以及拦截器的配置
一.自定义拦截器 Spring MVC也可以使用拦截器对请求进行拦截处理,用户可以自定义拦截器来实现特定的功能,自定义的拦截器必须实现HandlerInterceptor接口. 二.HandlerIn ...
随机推荐
- alibaba开发手册
alibaba开发手册 11.19 强制: 方法参数在定义和传入时,多个参数逗号后边必须加空格. IDE 的 text file encoding 设置为 UTF-8; IDE 中文件的换行符使用 ...
- MySQL之单表多表查询
#1.单表查询 #单表查询语法 select <字段1,字段2....> from <表名> where <表达式> group by field 分组 havin ...
- HTML常用表单标签
1.表单元素 <form> HTML 表单用于收集用户输入. 代码示例: <form action="http://xxx.xxx.xxx/xxx.php" me ...
- 如何在PHP7中扩展mysql,先安装php7.2。后安装mysql
相对与PHP5,PHP7的最大变化之一是移除了mysql扩展,推荐使用mysqli或者pdo_mysql,实际上在PHP5.5开始,PHP就着手开始准备弃用mysql扩展,如果你使用mysql扩展,可 ...
- opt目录
在linux环境测试时,会部署到/opt目录下,这是为何呢? 下面来详解Linux的/opt目录: /opt:用户级的程序目录 这里主要存放那些可选的程序. 比如,你想部署firefox测试版,那就装 ...
- Python自定义模块
自定义模块 自定义模块(也就是私人订制),我们要自定义模块,首先就要知道什么是模块 一个函数封装一个功能,比如现在有一个软件,不可能将所有程序都写入一个文件,所以咱们应该分文件,组织结构要好,代码不冗 ...
- SQL逗号合并一列多行的值
select stuff((select ','+行名 from 表名 for xml path('')),1,1,'')
- 11.C++ 动态内存管理
在dll中malloc的内存, 必须要在dll中free掉,否则无法编译通过 //dll文件 #include <stdio.h> #include <iostream> #d ...
- juery 实现选项卡
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- Hadoop集群搭建(一)~虚拟机的创建
Hadoop集群的搭建包括,虚拟机系统的安装:安装JDK,Hadoop:克隆虚拟机:伪分布式的搭建:安装zookeeper:Hive:Hbae:Spark等等: 我将分为多篇文章来记录.这篇文章主要写 ...