Filter过滤指定ip地址

web.xml配置



  

  

        

    

    index.jsp  

    

    

   


      MyFilter  

      www.MyFilter  

   


    

   


      MyFilter  

        

      /*  

      

   
  

  









servlet代码



package www;

 

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;

 

public class MyFilter implements Filter{

 

 

       @Override

       public void doFilter(ServletRequest request, ServletResponse response, FilterChain
chain)throws IOException, ServletException {

              //
TODO Auto-generated method stub

              HttpServletRequest request1  = (HttpServletRequest)request;

              HttpServletResponse  response1 = (HttpServletResponse)response;

                String ip = request.getRemoteAddr() + "";
		System.out.println("the ip is"+ip);
      
int ad = Integer.parseInt(ip.substring(ip.lastIndexOf(".") +1));

       


       
if(ad >= 1 && ad <= 50){

           
response.setContentType("text/html;charset=utf-8");

           
//跳转到error.jsp

           
request1.getRequestDispatcher("error.jsp").forward(request1,
response1);

       
}

       
else{           
chain.doFilter(request, response);
    }

      }

       @Override
       public void destroy() {

              //TODO Auto-generated method stub
       }

       @Override

       public void init(FilterConfig arg0) throws ServletException {

              //TODO Auto-generated method stub

              System.out.println("MyFilter.init(我被初始化了)");
       }
    
}

login.jsp

<%@ page language="java" contentType="text/html;
charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>









Insert title here





this is login page

error.jsp



<%@ page language="java" contentType="text/html;
charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>









Insert title here





this is error page

运行登陆界面,ip会被过滤,跳转执行错误界面内容。

运行截图

Filter过滤指定ip地址_第1张图片

你可能感兴趣的:(servlet)