如何过滤非法IP地址的用户发送请求

实现步骤: 

1.  创建自己的RequestProcessor类,重写体重的proccessPreprocess加入所需的控制逻辑.源代码如下:

package classmate;

注意导包: commons-logging.jar

2. struts-config.xml文件配置如下:

加入:

 

 

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.RequestProcessor;

import org.apache.struts.config.ForwardConfig;
import org.apache.commons.logging.Log;

/**
 * 繼承RequestProcessor類
 * @author java
 *
 */
public class MyRequestProcessor extends RequestProcessor {
/**
 * 無參數的構造方法
 *
 */
 public MyRequestProcessor() {
 }
/**
 * 重寫processpreprocess()方法
 */
 protected boolean processPreprocess(HttpServletRequest request,
   HttpServletResponse response) {

  boolean continueProcessing = true;
  //獲取發出請求的的客戶端IP地址
  // Get the name of the remote host and log it
  String remoteHost = request.getRemoteHost();
  log.info("Request from host: " + remoteHost);
  //判斷地址的合法性
  // Make sure the host is from one that you expect
  if ((remoteHost == null || !remoteHost.startsWith("127."))) {
   // Not the localhost, so don't allow the host to access the site
   continueProcessing = false;

   try {
    //跳轉到錯誤頁面
    response.sendRedirect("/S02_Extend/error.jsp");
   } catch (Exception ex) {
    log.error("Problem sending redirect from processPreprocess()");
   }
  }
  return continueProcessing;
 }

}

你可能感兴趣的:(Struts相关)