servlet利用filter实现登录过滤

登录过滤类loginFilter
------------------------------------------

package spell;
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 loginFilter extends HttpServlet implements Filter {
    
     private FilterConfig filterConfig;
//Handle the passed-in FilterConfig
     public void init(FilterConfig filterConfig) throws ServletException {
         this.filterConfig = filterConfig;
     }
//Process the request/response pair
     public void doFilter(ServletRequest request, ServletResponse response,
             FilterChain filterChain) {
         try {
                 HttpServletRequest req=(HttpServletRequest)request;
                 HttpServletResponse rsp=(HttpServletResponse)response;
                 HttpSession session=req.getSession(true);
                 String userName=(String)session.getAttribute("userName");
                 if(userName!=null)
                 {//验证通过
                      filterChain.doFilter(request, response);
                 }
                 else
                 {//验证不通过,取得设置的跳转页面参数
                     String noLogin=filterConfig.getInitParameter("noLogin");
                     rsp.sendRedirect(noLogin);
                 }
         } catch (Exception sx) {
             filterConfig.getServletContext().log(sx.getMessage());
         }
        
     }
    
//Clean up resources
     public void destroy() {
     }
    
     protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
         super.doGet(arg0, arg1);
     }
    
     protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
         super.doPost(arg0, arg1);
     }
}

web.xml配置
----------------------------

     <filter>
         <filter-name>loginFilter</filter-name>
         <filter-class>spell.loginFilter</filter-class>   <!--loginFilter对应的类名-->
         <init-param>
             <param-name>noLogin</param-name>
             <param-value>../strutsHtml.jsp</param-value> <!--没有登录跳转的页面-->
         </init-param>
     </filter>

     <filter-mapping>
         <filter-name>loginFilter</filter-name>   <!--选择loginFilter来验证登录-->
         <url-pattern>/member/*</url-pattern>   <!--配置member下的文件要求权限判断-->
     </filter-mapping>

你可能感兴趣的:(servlet)