Spring Boot Learning (12) interceptor implements IP blacklist

Source: Internet
Author: User


Interceptor Implementation IP blacklist preface


Recently has been engaged in hexo+githubpage build personal blog, so not how to carry out springboot study. So today we have made a modification to the last "? Seconds anti-refresh". The last time the feature was implemented with annotations and interceptors (@Aspect). However, if the demand is a global interceptor for most of the URLs are intercepted, it is obviously impossible to add their own. And the last interceptor for the controller parameters are required, in the actual other references always appear inconvenient. So, this time using inheritanceHandlerInterceptorto implement interceptors.


Functional Requirements


For a certain type of URL in the project to intercept, if the user in a short period of time to access the link, the User IP is blacklisted, prohibit users from accessing the Web page. (At the same time, you can use@Asyncto create timed tasks to unblock users.) )


Get ready? Seconds of anti-refresh business logic


Blog Address: http://blog.csdn.net/u011244202/article/details/54783337
Project Reference Address: Https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B5


Springboot+druid+mybatis


Blog Address: http://blog.csdn.net/u011244202/article/details/54709060
Project Reference Address: https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B1


Knowledge record


Spring's Interceptor Handlerinterceptor functions like a filter, but provides finer control: Before the request is answered, after the request is answered, before the view is rendered, and after the request is complete. We cannot modify the request content through interceptors, but we can pause the execution of the request by throwing an exception (or returning false).
Configuring interceptors is also simple, Spring provides the base class Webmvcconfigureradapter, and we only need to rewrite the Addinterceptors method to add a registered interceptor.



It only takes 3 steps to implement a custom interceptor:
1. Create our own interceptor class and implement the Handlerinterceptor interface.
2. Create a Java class to inherit Webmvcconfigureradapter, and override the Addinterceptors method.
3. Instantiate our custom interceptor, and then manually add the image to the interceptor chain (added in the Addinterceptors method).


Official Start IP Tool class


Due to the unclear user agent, it is best to use a tool class to obtain the user's real IP. This Google will be able to find, I will not post code.


Database


I am using the MySQL database, the persistence layer framework is mybatis. Refer to the "prepare" step for details.
I created a table "Blaclist" in the "Myboot" database with the following properties:


Field name explain
Id ID of the record
Ip User Real IP
Iptime IP locked Time
Entity class

Public class BlackList {

Private int id;
Private IP String;
Private Date iptime; // date type, format: yyyy-mm-dd HH: MM :ss
/ / the constructor
Public BlackList () {
}

Public BlackList(String IP, Date iptime) {
This. IP = IP;
Enclosing iptime = iptime;
}
// get && set method
}




DAO layer


Note The XML configuration is configured with the corresponding entity (omitted).



@Mapper
public interface BlackListDao {
//Find records by IP
List<BlackList> findByIp(String ip);
//Add record
int addBlackList(@Param("blackList") BlackList blackList);
}


Implementing the Handlerinterceptor Interface


public class URLInterceptor implements HandlerInterceptor {
@Autowired
BlackListDao blackListDao;
private Map<String, Integer> redisTemplate = new HashMap<String, Integer>();
private static final Logger logger = LoggerFactory.getLogger(URLInterceptor.class);
//Call before request processing (before controller method call)
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
Return true;
}
//Call after request processing, but before the view is rendered (after controller method call)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
String ip = IPAddressUtil.getClientIpAddress(httpServletRequest);
List<BlackList> blackLists = blackListDao.findByIp(ip);
if (blackLists == null || blackLists.size() == 0){
urlHandle(httpServletRequest, 5000, 10);
} else {
//Forced control jump
modelAndView.setViewName("/errorpage/error.html");
}
}
//Called after the end of the entire request
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
public void urlHandle(HttpServletRequest request, long limitTime,int limitCount) throws RequestLimitException {
* *
*Omit the business logic section, refer to the "preparation" step
* /
If (count > limitcount) {/ / the lock condition is met
Calendar calendar = Calendar.getInstance();
Date iptime=calendar.getTime();
BlackList blackList = new BlackList(ip, iptime);
blackListDao.addBlackList(blackList);
throw new RequestLimitException();
}
}
}




Webmvcconfigureradapter class


Configure the Interceptor Webmvcconfigureradapter for spring MVC.



@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Bean / / inject our interceptor as bean
public HandlerInterceptor getMyInterceptor(){
return new URLInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//Multiple interceptors form an interceptor chain
//Addpathpatterns is used to add interception rules. Here we assume that all links after interception / url
//Excludepathpatterns user exclusion
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/url/**");
super.addInterceptors(registry);
}
}


Controller class



 @RequestMapping("/url/test")
    @ResponseBody
    public String URLtest() {
        return "success";
    }





Spring Boot Learning (12) interceptor implements IP blacklist


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.