有关于自己目前的对于filter的用法吧
备注,之下所写代码,不是测试代码,是直接把之前代码copy下来的,并不能直接运行,只是拿来当个借鉴
首先,是有关filter在web.xml配置文件中的配置
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>filter.loginFilter</filter-class>
<init-param>
<param-name>ex</param-name>
<param-value>login.jsp,.css,.eot,.woff,.ttf,.png,.jpg,Activity_User/login,Activity_Operator/login,.js,img</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
接下来
public class loginFilter implements Filter{
private Set<String> prefixIignores = new HashSet<String>();
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req1, ServletResponse resp1, FilterChain fc)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req=(HttpServletRequest) req1;
HttpServletResponse resp=(HttpServletResponse) resp1;
if (canIgnore(req)) {
fc.doFilter(req, resp);
return;
}
if(req.getSession().getAttribute("operator")!=null||req.getSession().getAttribute("user")!=null) {
fc.doFilter(req, resp);
}
else {
resp.sendRedirect("http://localhost:8080/activity/login.jsp");
}
}
public void init(FilterConfig c) throws ServletException {
String ex = c.getInitParameter("ex");
String[] ignoreArray = ex.split(",");
for (String s : ignoreArray) {
prefixIignores.add(s);
}
}
private boolean canIgnore(HttpServletRequest request) {
String url = request.getRequestURI();
for (String ignore : prefixIignores) {
if (url.endsWith(ignore)) {
return true;
}
}
return false;
}
}
版权声明:本文为lzy_cherubim原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。