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>
相关新闻>>
- 发表评论
-
- 最新评论 更多>>