jsp---Filter的使用
struts2中的拦截器可以拦截action,但是无法拦截页面的请求,但是有些页面需要有权限才可以访问,不可以直接访问,有一种解决的办法就是使用Filter
1、创建Filter类,需要实现Filter接口:
[java]
package filter;
import java.io.IOException;
import java.util.Map;
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;
import model.Admin;
public class LoginFilter implements Filter {
//private Map session;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
HttpSession session = request.getSession();
Admin admin = (Admin) session.getAttribute("nowUser");
System.out.println(admin);
if(admin == null){
response.sendRedirect("login.html");
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
在doFilter中实现过滤功能,这里主要是验证用户请求index.html页面时是否登录,如果登录则继续运行,否则返回到登录页面
还需要配置web.xml:添加下面的代码
[html]
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/index.html</url-pattern>
</filter-mapping>
配置文件的几种不同的情况:
1、过滤所有的请求:
[html]
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、过滤制定类型的请求:只过滤“.html”的文件
[html]
filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
3、过滤多种类型的:需要配置两个<filter-mapping>
[html]
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
4、过滤指定文件:就是刚才的情况,注意加“/”
[html]
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/index.html</url-pattern>
</filter-mapping>
上一篇: 使用Excel 录入一些带图形的数据时如何录入长方形
下一篇: 小儿按摩常用什么介质