一,何为面向方面编程?
面向方面编程(AOP)旨在向已有代码或应用增加行为来解决普遍关注点。在开发过程中,我们常常会收到新的关于日志或安全的需求。虽然日志代码都是一些重复性的代码,但这种需求却需要我们花费大量时间对已有代码进行重构。无论是出现在开发阶段还是项目设计阶段,这种普遍关注点都称为横切关注点,可以通过AOP解决
可以动态向运行中的代码添加所需的行为。它们会动态装饰方法的调用,就好像装饰模式,装饰对象一样
二,使用普通代码实现AOP
在JAVA WEB中可以通过servlet来拦截请求或是应用,这与方面很类似。要实现Servlet过滤器,我们需要创建一个类文件实现Servlet接口。
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class SecurityFilter implements Filter {
@SuppressWarnings("unused")
private FilterConfig filterConfig = null;
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
System.out.println(((HttpServletRequest) request).getRemoteAddr());
// perform some security check
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
@WebFilter(filterName = "TimeOfDayFilter", urlPatterns = { "/*" })
public class SecurityFilter3 implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
System.out.println(((HttpServletRequest) request).getRemoteAddr());
// perform some security check
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}