前言,第一次配置过滤器遇到了一些问题,研究了两天总结出点规律:没搞懂之前不要轻易的copy别人的代码,.很多人查一下代码直接copy web.xml文件的过滤配置,却不懂
<url-pattern>是什么意思。
一,配置过滤器: SSH项目很多页面的跳转都是通过action执行的,而不是写一个<a href="jsp1/Add.jsp">Forward to Filter URL</a>这样的路径直接跳转的,如果都是通过action跳转的只要在web.xlm配置就可以全过滤了:
<filter-name>filterTest</filter-name>
<filter-class>com.dwg.FilterAndListener.FilterTest</filter-class>
</filter>
<filter-mapping>
<filter-name>filterTest</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
对应的filter类:
package com.dwg.Filter;
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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class FilterTest extends HttpServlet implements Filter {
/**
*
*/
private static final long serialVersionUID = 1L;
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest httpReq=(HttpServletRequest)req;
HttpServletResponse httpRes=(HttpServletResponse)res;
HttpSession httpSession=httpReq.getSession();
String url = httpReq.getRequestURI();
//System.out.println(url);
if(httpSession.getAttribute("username")==null){
if(url.endsWith("index.jsp") || url.endsWith("LoginUser.action") ){
chain.doFilter(req, res);
}
else{
//System.out.println("User对象空值");
httpRes.sendRedirect(httpReq.getContextPath()+"/index.jsp");
}
}else{
//System.out.println("cale");
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
二。很多页面跳转是用的<a href="jsp1/Add.jsp">Forward to Filter URL</a>这样的方式的话web.xml配置就要过滤子目录:
<filter-name>filterTest</filter-name>
<filter-class>com.dwg.FilterAndListener.FilterTest</filter-class>
</filter>
<filter-mapping>
<filter-name>filterTest</filter-name>
<url-pattern>/jsp1/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filterTest</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
三。也就是说<url-pattern>内容取决你你访问页面的方式 把所有的.jsp文件放到一个文件夹下,但是访问方式为action方式,web.xml再用子目录过滤(<url-pattern>/jsp1/*</url-pattern>)是不生效的。