filter实现登录验证,并且过滤servlet

 

登录html:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Login</title>
  </head>
  <body>
    Login<br>
   
    <form action="servlet/Login" method="post">
     UserName:<input type="text" name="username"/><br/>
     Password:<input type="text" name="password"/><br/>
     <input type="submit" value="Login"/>
    </form>
  </body>
</html>

 


 

登录servlet判定类,就是中间简单的充当业务逻辑的判定类

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
/**
 *
 * @author zwc
 *
 */
@SuppressWarnings("serial")
public class Login extends HttpServlet {
 private Logger logger = Logger.getLogger(this.getClass());
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException{
  doPost(request,response);
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  response.setCharacterEncoding("UTF-8");
  request.setCharacterEncoding("UTF-8");
  PrintWriter out = response.getWriter();
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  HttpSession session = request.getSession();
  
  if("zhangwc".equals(username) && "123456".equals(password)){  注意:逻辑判定,就这一句
   session.setAttribute("isLogin", true);
   logger.info("登录成功");
  }else{
   session.setAttribute("isLogin", false);
   logger.info("登录失败");
  }
  //RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
  //rd.forward(request, response);
 }
}

 


 

过滤类,需要实现filter接口

 

 

package 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;

import org.apache.log4j.Logger;

/**
 *
 * @author zwc
 *
 */

public class LoginFilter implements Filter {
 private Logger logger = Logger.getLogger(this.getClass());
 private String excludeDirs[];
 private boolean isExclude = false;
 private String contextPath;
 public void doFilter(ServletRequest servletrequest,
   ServletResponse servletresponse, FilterChain filterchain)
   throws IOException, ServletException {
  HttpServletRequest request = (HttpServletRequest) servletrequest;
  HttpServletResponse response = (HttpServletResponse) servletresponse;
  HttpSession session = request.getSession(true);

  String path = request.getServletPath();  得到当前请求的路径
  int start = path.indexOf("*");
  
  for(String requestPath : excludeDirs){
   if(requestPath.indexOf(path) != -1){  如果该路径在文档中存在,或者包括,则跳过,
    logger.info("请求路径为:" + path +" .......放过");
    filterchain.doFilter(servletrequest, servletresponse);  注意这里要加,过滤链,否则对应的servlet不会指向
   }else{
    logger.info("请求路径为:" + path +" .......不放过,过滤");
    Object o =  session.getAttribute("isLogin");session判定
    logger.info("请求经过过滤器,isLogin:" + o);
    if(o != null && ((Boolean)o == Boolean.TRUE)){
     filterchain.doFilter(servletrequest, servletresponse);
    }else{
//     RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
     response.sendRedirect(contextPath + "/login.jsp");
    }   
   }
  }
 }
 public void init(FilterConfig filterconfig) throws ServletException {
  excludeDirs = filterconfig.getInitParameter("exclude").split(";");

得到初始化时,定义的,过滤白名单中,不用过滤的目录和文件,不支持   “ *
  contextPath = filterconfig.getServletContext().getContextPath();

得到文档的上下文路径 
 }
 public void destroy() {
 }
}


 

 

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <context-param>
  <param-name>username</param-name>
  <param-value>yuanfen</param-value>
 </context-param>
 
 <!-- security setting  -->
 <!-- 
 <security-constraint>
  <web-resource-collection>
   <web-resource-name>protectedArea1</web-resource-name>
   <url-pattern>/*</url-pattern>
  </web-resource-collection>
  <auth-constraint>
   <role-name>manager</role-name>
  </auth-constraint>
 </security-constraint>
 <login-config>
  <auth-method>BASIC</auth-method>
  <realm-name>protectedArea1</realm-name>
 </login-config>
 -->
 
 
 <jsp-config>
  <taglib>
   <taglib-uri>/test-1.0</taglib-uri>
   <taglib-location>test-1.0.tld</taglib-location>
  </taglib>
 </jsp-config>

 <!-- session config -->
 <session-config>
  <session-timeout>-1</session-timeout>
 </session-config>
 
 
 <!-- ajaxanywhere setting -->

 <!-- filter setting -->
 <filter>
  <description>支持,文件和路径。不支持    *  处理</description>
  <filter-name>LoginFilter</filter-name>
  <filter-class>filter.LoginFilter</filter-class>
  <init-param>
   <param-name>exclude</param-name>
   <param-value>/servlet/Login;</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>LoginFilter</filter-name>
  <url-pattern>/servlet/*</url-pattern>
 </filter-mapping>

 
 

 <!-- servlet config -->
  <servlet>
    <servlet-name>Login</servlet-name>
    <servlet-class>servlet.Login</servlet-class>
  </servlet>

 

  <servlet-mapping>
    <servlet-name>Login</servlet-name>
    <url-pattern>/servlet/Login</url-pattern>
  </servlet-mapping>

 
 
 
 
 <error-page>
  <exception-type>java.lang.Exception</exception-type>
  <location>/error.jsp</location>
 </error-page> 
 <error-page>
  <error-code>500</error-code>
  <location>/error.jsp</location>
 </error-page>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>


 

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值