通过本机IP作为访问网站服务器限制条件

    技术2022-05-12  1

    2009年5月7号  星期四  天气晴

     

     

             今天完成了通过本机IP作为访问网站服务器限制条件的实现,主要是通过Filter来完成的,再加上struts2的应用,

     

    通过读取IPINFO的配置文件,得到不受限制的IP或者是IP段,检测发来请求的客户端的IP地址,是否属于配置文件中的IP

     

    段,如果属于,通过struts2配置,将其放行,可以正常访问网页,如果不属于,转到登录页面,如果登录成功,放行,否

     

    则,退回登陆页面。

     

    具体实现代码:

     

     

    IPINFO配置文件

     

     

    =============================我是分割线==============================

     

    读取配置文件的代码

    ReadIPInfoFileUtil2。java

     

    package g.cms.util;

    import java.io.IOException;import java.io.InputStream;import java.util.LinkedList;import java.util.List;import java.util.Properties;

    import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;

    /** * @author Jane(吴贞贞) * @email myhongkongzhen@gmail.com * @since JDK 1.6 * @alter 2009年5月7号 * @version 1.0 2009年5月7号 */public class ReadIPInfoFileUtil2 { private static final Log log = LogFactory.getLog(ReadIPInfoFileUtil2.class); private static Properties ipInfoPro = new Properties(); static {  log.debug("IPInfo.properties loading...");  InputStream is = null;

      try {   is = ReadIPInfoFileUtil2.class.getClassLoader()     .getResourceAsStream("IPInfo.properties");   ipInfoPro.load(is);   log.debug("cIPInfo.properties load success!");  } catch (IOException e) {   log.debug("LOAD IPInfo.properties ERROR!");   e.printStackTrace();  } }

     

    //测试用的

     public static void main(String[] args) {  System.out.println(ReadIPInfoFileUtil2.test());

      List<String> ipInfosList = ReadIPInfoFileUtil2.readIPInfos();  for (String ipInfo : ipInfosList) {   System.out.println(ipInfo);

       if ("127.0.0.13".indexOf(ipInfo) == 0) {    System.out.println(ipInfo + " == OK");   } else {    System.out.println("ERROR");   }  } }

     public static String test() {  return ipInfoPro.getProperty("IP45"); }

     public static List<String> readIPInfos() {

      List<String> ipInfosList = new LinkedList<String>();  for (int i = 0;; i++) {   String ipInfo = ipInfoPro.getProperty("IP" + i);   if (null == ipInfo || "".trim().equals(ipInfo)) {    break;   } else {    ipInfosList.add(ipInfo);   }  }

      return ipInfosList;

     }}

     

     

    =============================我是分割线==============================

     IP限制的核心代码:

    IPFilter.java

     

    package g.web.filter;

    import g.cms.util.ReadIPInfoFileUtil2;

    import java.io.IOException;import java.util.List;import java.util.Map;

    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.commons.logging.Log;import org.apache.commons.logging.LogFactory;

     

    /** * @author Jane(吴贞贞) * @email myhongkongzhen@gmail.com * @since JDK 1.6 * @alter 2009年5月7号 * @version 1.0 2009年5月7号 */

     

    public class IPFilter implements Filter {

     private static final Log log = LogFactory.getLog(IPFilter.class);

     @Override public void destroy() {  // TODO Auto-generated method stub

     }

     @Override public void doFilter(ServletRequest request, ServletResponse response,   FilterChain chain) throws IOException, ServletException {  // TODO Auto-generated method stub

      request.setCharacterEncoding("utf8");  response.setContentType("text/html;charset=utf8");

      HttpServletRequest req = (HttpServletRequest) request;  HttpServletResponse resp = (HttpServletResponse) response;

      HttpSession session = req.getSession(true);  Map<String, Object> usr_map = (Map<String, Object>) session    .getAttribute("USR_MAP");

      if (usr_map == null) {   log.debug("用户对象为空,当前用户还没有登录");

       String remortIp = getRemortIP(req);   log.debug("REQUEST PATH FIRST : " + remortIp);

       List<String> ipInfosList = ReadIPInfoFileUtil2.readIPInfos();   // log.debug("IP SIZE : " + ipInfosList.size());   String rightIpInfo = null;   for (String ipInfo : ipInfosList) {    // if (!ipInfo.trim().equals(remortIp.trim())) {    // log.debug("====ERROR IP INFO=====");    // } else {    // log.debug("---OK IP INFO---");    // rightIpInfo = ipInfo;    // }

        if (remortIp.indexOf(ipInfo) == 0) {     log.debug("---OK IP INFO---");     rightIpInfo = ipInfo;     log.debug("IP INFO : " + rightIpInfo);    } else {     log.debug("====ERROR IP INFO=====");    }

       }

       if (null == rightIpInfo || "".trim().equals(rightIpInfo.trim())) {    log.debug("用户请求规定IP之外的页面资源,却没有登录,即将跳转到login.jsp");    req.getRequestDispatcher("login.jsp").forward(req, resp);   } else {    log.debug("用户请求规定IP之内的页面资源,不受限制,让其放行。。。");    chain.doFilter(req, resp);   }

      } else {   log.debug("用户已经登录,让其放行.....");   request.setAttribute("userName", usr_map.get("name"));   chain.doFilter(request, response);// 执行其他过滤器  }

     }

    //用来获得客户端的IP地址的方法

     private String getRemortIP(HttpServletRequest request) {  if (request.getHeader("x-forwarded-for") == null) {   return request.getRemoteAddr();  }  return request.getHeader("x-forwarded-for"); }

     @Override public void init(FilterConfig arg0) throws ServletException {  // TODO Auto-generated method stub

     }

    }

     

    =============================我是分割线==============================

    登录页面login.jsp

     

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://"   + request.getServerName() + ":" + request.getServerPort()   + path + "/";%>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head>  <base href="<%=basePath%>">

      <title>网站前台登陆</title>

      <meta http-equiv="pragma" content="no-cache">  <meta http-equiv="cache-control" content="no-cache">  <meta http-equiv="expires" content="0">  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  <meta http-equiv="description" content="This is my page">  <link rel="stylesheet" type="text/css"   href="<%=basePath%>styles/form.css"></link>

     </head>

     <body>  <center>   <h1>    您的IP不在规定访问权限IP(段)列表中,请通过登录程序访问资源   </h1>  </center>  <form action="user!loginUser.do" method="post">   <table align="center" border="1" cellpadding="0" cellspacing="0">    <tr>     <td>      用户名     </td>     <td>      <input type="text" name="user.userid" />     </td>    </tr>    <tr>     <td>      密码     </td>     <td>      <input type="password" name="user.password" />     </td>    </tr>    <tr>     <td align="right">      <input type="submit" value="登录">     </td>     <td align="left">      <input type="reset" value="取消">     </td>    </tr>   </table>  </form> </body></html> 

     

    =============================我是分割线==============================

    struts2的action代码

     

    /** * @author Jane(吴贞贞) * @email myhongkongzhen@gmail.com * @since JDK 1.6 * @alter 2009年5月7号 * @version 1.0 2009年5月7号 */

    public String loginUser() {  log.debug("/n-----------------登錄驗證操作--------------------/n");  Map params = request.getParameterMap();

      String userName = request.getParameter("user.userid");  String password = request.getParameter("user.password");

      if (StringUtils.isEmpty(userName)) {   // request.setAttribute("msg", "用户名不能为空");   log.debug("用户名不能为空");   return "loginUser";  }  if (StringUtils.isEmpty(password)) {   // request.setAttribute("msg", "密码不能为空");   log.debug("密码不能为空");   return "loginUser";  }

      UserService service = new UserService();  String sql = "select * from manager where userid=? and password=?";  List<?> result = service.query(sql, userName, password);  if (result.size() > 0) {   HttpSession session = request.getSession();   Map<String, Object> user_map = (Map<String, Object>) result.get(0);   session.setAttribute("USR_MAP", user_map);   return "indexUser";  } else {   // request.setAttribute("msg", "用户不存在");   log.debug("用户不存在");   return "loginUser";  } }

     

     

    =============================我是分割线==============================

    struts2的配置文件struts.xml

     

    <action name="user" class="g.cms.web.action.UserAction">   <result name="target">/admin/user/user_info.jsp</result>   <result name="manager" type="freemarker">    /admin/user/user_manager.ftl   </result>   <result name="index" type="redirect">    /admin/index.jsp   </result><!-- 重定向到主页为的就是是浏览器地址栏发生变化 -->   <result name="login" type="redirect">    /admin/login.jsp   </result>   <result name="loginUser" type="redirect">login.jsp</result>   <result name="indexUser" type="redirect">index.jsp</result>   <result name="groupManager">    /admin/user/user_group_manager.ftl   </result>   <result name="editGroup">    /admin/user/edit_user_group.jsp   </result>  </action>

     

    =============================我是分割线==============================

     

    以上是实现IP限制的核心代码,如果有不明白的地方,请联系我qq511134962,msn:myhongkongzhen@gmail.com


    最新回复(0)