SpringBoot中自定義注解實(shí)現(xiàn)控制器訪問次數(shù)限制實(shí)例
今天給大家介紹一下SpringBoot中如何自定義注解實(shí)現(xiàn)控制器訪問次數(shù)限制。
在Web中最經(jīng)常發(fā)生的就是利用惡性URL訪問刷爆服務(wù)器之類的攻擊,今天我就給大家介紹一下如何利用自定義注解實(shí)現(xiàn)這類攻擊的防御操作。
其實(shí)這類問題一般的解決思路就是:在控制器中加入自定義注解實(shí)現(xiàn)訪問次數(shù)限制的功能。
具體的實(shí)現(xiàn)過程看下面的例子:
步驟一:先定義一個(gè)注解類,下面看代碼事例:
package example.controller.limit;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
//最高優(yōu)先級(jí)
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
/**
*
* 允許訪問的次數(shù),默認(rèn)值MAX_VALUE
*/
int count() default Integer.MAX_VALUE;
/**
*
* 時(shí)間段,單位為毫秒,默認(rèn)值一分鐘
*/
long time() default 60000;
}
步驟二:定義一個(gè)異常類,用來處理URL攻擊時(shí)產(chǎn)生的異常問題,下面看代碼事例:
package example.controller.exception;
public class RequestLimitException extends Exception {
private static final long serialVersionUID = 1364225358754654702L;
public RequestLimitException() {
super("HTTP請(qǐng)求超出設(shè)定的限制");
}
public RequestLimitException(String message) {
super(message);
}
}
步驟三:定義一個(gè)注解的具體實(shí)現(xiàn)類,下面看代碼事例:
package example.controller.limit;
import example.controller.exception.RequestLimitException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
@Aspect
@Component
public class RequestLimitContract {
private static final Logger logger = LoggerFactory.getLogger("RequestLimitLogger");
private Map<String, Integer> redisTemplate=new HashMap<String,Integer>();
@Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)")
public void requestLimit(final JoinPoint joinPoint, RequestLimit limit) throws RequestLimitException {
try {
Object[] args = joinPoint.getArgs();
HttpServletRequest request = null;
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof HttpServletRequest) {
request = (HttpServletRequest) args[i];
break;
}
}
if (request == null) {
throw new RequestLimitException("方法中缺失HttpServletRequest參數(shù)");
}
String ip = request.getLocalAddr();
String url = request.getRequestURL().toString();
String key = "req_limit_".concat(url).concat(ip);
if(redisTemplate.get(key)==null || redisTemplate.get(key)==0){
redisTemplate.put(key,1);
}else{
redisTemplate.put(key,redisTemplate.get(key)+1);
}
int count = redisTemplate.get(key);
if (count > 0) {
Timer timer= new Timer();
TimerTask task = new TimerTask(){ //創(chuàng)建一個(gè)新的計(jì)時(shí)器任務(wù)。
@Override
public void run() {
redisTemplate.remove(key);
}
};
timer.schedule(task, limit.time());
//安排在指定延遲后執(zhí)行指定的任務(wù)。task : 所要安排的任務(wù)。10000 : 執(zhí)行任務(wù)前的延遲時(shí)間,單位是毫秒。
}
if (count > limit.count()) {
//logger.info("用戶IP[" + ip + "]訪問地址[" + url + "]超過了限定的次數(shù)[" + limit.count() + "]");
throw new RequestLimitException();
}
} catch (RequestLimitException e) {
throw e;
} catch (Exception e) {
logger.error("發(fā)生異常: ", e);
}
}
}
步驟四:實(shí)現(xiàn)一個(gè)控制類,并添加使用注解功能。下面看代碼事例:
package example.controller;
import example.controller.limit.RequestLimit;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
public class URLController {
@RequestLimit(count=10,time=5000)
@RequestMapping("/urltest")
@ResponseBody
public String test(HttpServletRequest request, ModelMap modelMap) {
return "aaa";
}
}
其中count指的是規(guī)定時(shí)間內(nèi)的訪問次數(shù),time指的就是規(guī)定時(shí)間,單位為毫秒。
這樣就實(shí)現(xiàn)了在控制器這個(gè)層次上面的url攔截了。不過這里有個(gè)問題,就是如果想在每一個(gè)URL頁面上面都進(jìn)行這樣的攔截,這種方法明顯是不夠的。因?yàn)槲覀儾豢赡茉诿總€(gè)控制器上面都加上url攔截的注解,所以這種方法只適合在某些特定的URL攔截上面使用它們。
那如何實(shí)現(xiàn)過濾器級(jí)別上面的URL訪問攔截呢?這里先給大家賣一個(gè)關(guān)子,我將會(huì)在下一節(jié)中給大家介紹如何利用過濾器實(shí)現(xiàn)URl訪問攔截,并且利用JPA實(shí)現(xiàn)ip黑名單的功能,加入IP黑名單后就不可以進(jìn)行任何URL的訪問了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
一篇文章學(xué)會(huì)java死鎖與CPU 100%的排查
這篇文章主要介紹了一篇文章學(xué)會(huì)java死鎖與CPU 100%的排查,文中主要介紹了Java死鎖以及服務(wù)器CPU占用率達(dá)到100%時(shí)的排查和解決方法,感興趣的朋友一起來看一看吧2021-08-08
Java中JDBC實(shí)現(xiàn)動(dòng)態(tài)查詢的實(shí)例詳解
從多個(gè)查詢條件中隨機(jī)選擇若干個(gè)組合成一個(gè)DQL語句進(jìn)行查詢,這一過程叫做動(dòng)態(tài)查詢。下面通過實(shí)例代碼給大家講解JDBC實(shí)現(xiàn)動(dòng)態(tài)查詢的方法,需要的朋友參考下吧2017-07-07
Java中用內(nèi)存映射處理大文件的實(shí)現(xiàn)代碼
下面小編就為大家?guī)硪黄狫ava中用內(nèi)存映射處理大文件的實(shí)現(xiàn)代碼。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
spring/springboot整合dubbo詳細(xì)教程
今天教大家如何使用spring/springboot整合dubbo,文中有非常詳細(xì)的圖文介紹及代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴有很好地幫助,需要的朋友可以參考下2021-05-05
java 中JFinal getModel方法和數(shù)據(jù)庫使用出現(xiàn)問題解決辦法
這篇文章主要介紹了java 中JFinal getModel方法和數(shù)據(jù)庫使用出現(xiàn)問題解決辦法的相關(guān)資料,需要的朋友可以參考下2017-04-04
淺談spring-boot-rabbitmq動(dòng)態(tài)管理的方法
這篇文章主要介紹了淺談spring-boot-rabbitmq動(dòng)態(tài)管理的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12
Sprigmvc項(xiàng)目轉(zhuǎn)為springboot的方法
本篇文章主要介紹了Sprigmvc項(xiàng)目轉(zhuǎn)為springboot的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-02-02
linux環(huán)境下java程序打包成簡(jiǎn)單的hello world輸出jar包示例
這篇文章主要介紹了linux環(huán)境下java程序打包成簡(jiǎn)單的hello world輸出jar包,結(jié)合簡(jiǎn)單hello world輸出程序示例分析了Linux環(huán)境下的java可執(zhí)行jar包文件的生成相關(guān)操作技巧,需要的朋友可以參考下2019-11-11

