Filter作用 :
每当使用应用服务器页面或servlet的时候,应用服务器就会根据web.xml里面配置的filter 去进行过滤理。
调用处理过程就是:
1.接受request->去处理第一个filter.init-> 处理第一个filter.doFilter
2.如果不想继续使用filter过滤就在filter.doFilter中使用 return
3.如果要继续使用filter过滤就filter.doFilter中 chain.doFilter(servletRequest, servletResponse);
使用例子:
1.web.xml配置
<filter>
<filter-name>Filter_name</filter-name>
<filter-class>Filter_class_name</filter-class>
<init-param>
<description>set 'true' to enable the filter</description>
<param-name>enabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>excepts</param-name>
<param-value>Excepts_Path</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Filter_name</filter-name>
<url-pattern>filter_path</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Filter_name</filter-name>
<url-pattern>filter_path</url-pattern>
</filter-mapping>
2、java代码
2.1 init 函数
public void init(FilterConfig filterConfig) throws ServletException {
//检查是否打开SSOFilter功能
String _enable = filterConfig.getInitParameter("enabled");
if (_enable != null && "true".equalsIgnoreCase(_enable)) {
enabled = true;
}
//初始化例外列表,即不经过SSOFilter的请求地址
String _exceptStr = filterConfig.getInitParameter("excepts");
if (_exceptStr != null) {
String[] _excepts = _exceptStr.split(",");
for (int i = 0; i < _excepts.length; i ++) {
excepts.add(_excepts[i]);
}
}
}
2.2 doFilter函数
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String path = request.getServletPath();
/**
* 当WEB程序启了SSOFilter,并且请求的路径没被配置为例外时,
* 检查用户是否已通过统一用户平台登录,已登录的话创建会话,否则转到统一登录页面。
*/
if (enabled && !excepts.contains(path)) {
if (logger.isDebugEnabled()) {
logger.debug("check member has signoned ...");
}
boolean signOned = SSOHelper.hasSignOned(request, response);
if (logger.isDebugEnabled()) {
logger.debug("Signoned? " + signOned);
}
if (!signOned) {
String SSOContextUri = SysParamHelper.getSysParam(SysParamConstants.CONTEXT_URI_SSO);
StringBuffer url = new StringBuffer(SSOContextUri);
url.append("/Login");
//记住入口地址
url.append("?entrance=");
url.append(request.getRequestURL());
if (request.getQueryString() != null) {
url.append("|");
url.append(request.getQueryString());
}
response.sendRedirect(url.toString());
return;
}
}
chain.doFilter(servletRequest, servletResponse);
}