web应用中,我们经常使用filter机制来确定外部请求的用户是否登录,角色是否合法等。Spring提供了一个 DelegatingFilterProxy机制来完成filter的部分功能。通过例子做一个简单对比。 二者看起来没有什么太大的区别,在spring中,filter被纳入了bean 管理机制。
1.servlet filter
package servlet.filter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class LoginFilter implements Filter {
protected FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws java.io.IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String username = req.getParameter("j_username");
System.out.println("this is in servlet filter");
chain.doFilter(request, response);
}
}
-
web.xml
<filter>
<filter-name>simplelogin</filter-name>
<filter-class>servlet.filter.LoginFilter</filter-class>
<init-param>
<param-name>hello</param-name>
<param-value>hello filter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>simplelogin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2. Spring filter
-
LoginFilter.java
package filter;
import java.io.IOException;
import java.security.Principal;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.logging.*;
public class LoginFilter implements Filter {
private FilterConfig filterConfig = null;
Log log = LogFactory.getLog(LoginFilter.class);
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
Principal principal=request.getUserPrincipal();
HttpServletResponse response=(HttpServletResponse)res;
log.info("filter user name:"+request.getParameter("j_username")+":"+principal.toString());
log.info("filter password :"+request.getParameter("j_password"));
chain.doFilter(req,res);
}
public void init(FilterConfig config) throws ServletException {
this.filterConfig = config;
}
public void destroy() {
filterConfig = null;
}
}
-
web.xml
<filter>
<description>LoginFilter</description>
<display-name> LoginFilter</display-name>
<filter-name>LoginFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<description>
</description>
<param-name>targetBeanName</param-name>
<param-value>loginFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
-
spring context config
<bean id="filter" class="filter.LoginFilter" />