一,本例通过继承servlet下的Filter类并实现。
1,通过登陆页面触发session赋值来确认是否登陆,(详见:jsp:通过Session控制登陆时间和内部页面的访问)
2,此例修改为使用过滤器进行全站的网页权限控制。
以下是Fliter类中代码:
package com.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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class UserFilter implements Filter{ public void destroy() { // TODO Auto-generated method stub } //实现类doFilter进行权限的控制。 public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { HttpServletRequest req=(HttpServletRequest)arg0; HttpServletResponse res=(HttpServletResponse)arg1; HttpSession session=req.getSession(); String user=(String)session.getAttribute("user"); if(user==null||!"yes".equals(user)){ res.sendRedirect("/Tree/pages/login.jsp");//没有登陆过跳转到登陆页面 }else{ arg2.doFilter(arg0, arg1);//如果该session登陆过便放行 } } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
2,web.XML中配置:
在<
<?xml version="1.0" encoding="UTF-8"?> <display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>User</servlet-name>
<servlet-class>com.in.User</servlet-class>
</servlet>
<filter>
<filter-name>UserFilter</filter-name>
<filter-class>com.filter.UserFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserFilter</filter-name>
<url-pattern>/session/*</url-pattern>//选择需要过滤的文件夹下的所有网页
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>