There is the part of the UI Controller
@Controller
public class UiController {
...
@RequestMapping ( "/" )
public String summary ( HttpServletRequest request , HttpServletResponse response ) {
return "index" ;
}
@RequestMapping ( "/contacts" )
public String contacts ( HttpServletRequest request , HttpServletResponse response ) {
return "contacts" ;
}
@RequestMapping ( "/about" )
public String about ( HttpServletRequest request , HttpServletResp
return "about" ;
}
...
}
We need to check for every endpoint (methods): if a request comes from the ip which is contained in “blacklist” then error403.html (or what ever you want) should be returned.
@Controller
public class UiController {
@Resource
BlackList blackList ;
...
@RequestMapping ( "/" )
public String summary ( HttpServletRequest request , HttpServletResponse response ) {
if ( blackList . isIpInBlackList ( request . getRemoteAddr ()) {
response . setStatus ( HttpServletResponse . SC_FORBIDDEN );
return "errors/error403" ;
}
return "index" ;
}
@RequestMapping ( "/contacts" )
public String contacts ( HttpServletRequest request , HttpServletResponse response ) {
if ( blackList . isIpInBlackList ( request . getRemoteAddr ()) {
response . setStatus ( HttpServletResponse . SC_FORBIDDEN );
return "errors/error403" ;
}
return "contacts" ;
}
@RequestMapping ( "/about" )
public String about ( HttpServletRequest request , HttpServletResponse response ) {
if ( blackList . isIpInBlackList ( request . getRemoteAddr ()) {
response . setStatus ( HttpServletResponse . SC_FORBIDDEN );
return "errors/error403" ;
}
return "about" ;
}
...
}
AspectJ lets us to remove repeated “non business code” and place it to the “aspect”.
@Aspect
@Component
public class BlackListAspect {
@Resource
BlackList blackList ;
@Around ( "execution(* web.ui.UiController.*(..))" )
public String blackListFiltering ( ProceedingJoinPoint jp ) throws Throwable {
Object [] args = jp . getArgs ();
HttpServletRequest request = ( HttpServletRequest ) args [ 0 ];
HttpServletResponse response = ( HttpServletResponse ) args [ 1 ];
if ( blackList . isIpInBlackList ( request . getRemoteAddr ())) {
response . setStatus ( HttpServletResponse . SC_FORBIDDEN );
return "errors/error403" ;
}
Object result = jp . proceed ( args );
return result . toString ();
}
}
Aspect weaving
The last thing we need to setup is pom.xml
to properly weave our aspects.
There are some differences between Spring and non-Spring projects so carefully read this - Aspect weaving in Spring and non-Spring projects
You may also find these posts interesting: