SpringBoot中自定義注解實現(xiàn)控制器訪問次數(shù)限制實例
今天給大家介紹一下SpringBoot中如何自定義注解實現(xiàn)控制器訪問次數(shù)限制。
在Web中最經(jīng)常發(fā)生的就是利用惡性URL訪問刷爆服務(wù)器之類的攻擊,今天我就給大家介紹一下如何利用自定義注解實現(xiàn)這類攻擊的防御操作。
其實這類問題一般的解決思路就是:在控制器中加入自定義注解實現(xiàn)訪問次數(shù)限制的功能。
具體的實現(xiàn)過程看下面的例子:
步驟一:先定義一個注解類,下面看代碼事例:
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)先級
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
/**
*
* 允許訪問的次數(shù),默認(rèn)值MAX_VALUE
*/
int count() default Integer.MAX_VALUE;
/**
*
* 時間段,單位為毫秒,默認(rèn)值一分鐘
*/
long time() default 60000;
}
步驟二:定義一個異常類,用來處理URL攻擊時產(chǎn)生的異常問題,下面看代碼事例:
package example.controller.exception;
public class RequestLimitException extends Exception {
private static final long serialVersionUID = 1364225358754654702L;
public RequestLimitException() {
super("HTTP請求超出設(shè)定的限制");
}
public RequestLimitException(String message) {
super(message);
}
}
步驟三:定義一個注解的具體實現(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)建一個新的計時器任務(wù)。
@Override
public void run() {
redisTemplate.remove(key);
}
};
timer.schedule(task, limit.time());
//安排在指定延遲后執(zhí)行指定的任務(wù)。task : 所要安排的任務(wù)。10000 : 執(zhí)行任務(wù)前的延遲時間,單位是毫秒。
}
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);
}
}
}
步驟四:實現(xiàn)一個控制類,并添加使用注解功能。下面看代碼事例:
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ī)定時間內(nèi)的訪問次數(shù),time指的就是規(guī)定時間,單位為毫秒。
這樣就實現(xiàn)了在控制器這個層次上面的url攔截了。不過這里有個問題,就是如果想在每一個URL頁面上面都進行這樣的攔截,這種方法明顯是不夠的。因為我們不可能在每個控制器上面都加上url攔截的注解,所以這種方法只適合在某些特定的URL攔截上面使用它們。
那如何實現(xiàn)過濾器級別上面的URL訪問攔截呢?這里先給大家賣一個關(guān)子,我將會在下一節(jié)中給大家介紹如何利用過濾器實現(xiàn)URl訪問攔截,并且利用JPA實現(xiàn)ip黑名單的功能,加入IP黑名單后就不可以進行任何URL的訪問了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java中JDBC實現(xiàn)動態(tài)查詢的實例詳解
從多個查詢條件中隨機選擇若干個組合成一個DQL語句進行查詢,這一過程叫做動態(tài)查詢。下面通過實例代碼給大家講解JDBC實現(xiàn)動態(tài)查詢的方法,需要的朋友參考下吧2017-07-07
Java中用內(nèi)存映射處理大文件的實現(xiàn)代碼
下面小編就為大家?guī)硪黄狫ava中用內(nèi)存映射處理大文件的實現(xiàn)代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06
spring/springboot整合dubbo詳細(xì)教程
今天教大家如何使用spring/springboot整合dubbo,文中有非常詳細(xì)的圖文介紹及代碼示例,對正在學(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動態(tài)管理的方法
這篇文章主要介紹了淺談spring-boot-rabbitmq動態(tài)管理的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12
Sprigmvc項目轉(zhuǎn)為springboot的方法
本篇文章主要介紹了Sprigmvc項目轉(zhuǎn)為springboot的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
linux環(huán)境下java程序打包成簡單的hello world輸出jar包示例
這篇文章主要介紹了linux環(huán)境下java程序打包成簡單的hello world輸出jar包,結(jié)合簡單hello world輸出程序示例分析了Linux環(huán)境下的java可執(zhí)行jar包文件的生成相關(guān)操作技巧,需要的朋友可以參考下2019-11-11

