// 一個IP,是一個32位無符號的二進制數。故用long的低32表示無符號32位二進制數。
public long getIP(InetAddress ip) {
        
byte[] b = ip.getAddress();
        
long l = b[0<< 24L & 0xff000000L | b[1<< 16L & 0xff0000L
                
| b[2<< 8L & 0xff00 | b[3<< 0L & 0xff;
        
return l;
    }
在struts2相應的action中編寫如下判斷是否用戶是校內用戶的方法(方法參數中ip1的IP大小應該大于ip2的IP大小):
public void isSchoolUser(String ip1, String ip2) throws Exception {
         
// 得到用戶的IP地址
        String s = ServletActionContext.getRequest().getRemoteAddr();
        
long l = getIP(InetAddress.getByName(s));
         
// 設置IP地址段
        long l1 = getIP(InetAddress.getByName(ip1));
        
long l2 = getIP(InetAddress.getByName(ip2));
         
// 判斷用戶IP是否處在IP段中
        if (l >= l1 && l <= l2) {
        ActionContext.getContext().getSession().put(
"isSchoolUser","yes");
        }
    }

上面的方法中用到了InetAddress,所以需要引入java.net.InetAddress包;
接著再編寫IP攔截器如下:

public class IpAuthorityInterceptor extends AbstractInterceptor {
    
public String intercept(ActionInvocation invocation) throws Exception {
        ActionContext context 
= invocation.getInvocationContext();
        Map
<String, String> session = context.getSession();
        
if ("yes".equals(session.get("isSchoolUser"))){
            
return invocation.invoke();
        } 
else {
            context.put(
"AuthorityError""你是外網用戶無法訪問此資源");
            
return "error";
        }
    }
}


最后當然是配置IP攔截器,讓它為你工作吧:

interceptors>
            
<interceptor name="IpAuthorityInterceptor"
                
class="web.IpAuthorityInterceptor">
              
<!--此class對應你項目中的IpAuthorityInterceptor的編寫位置-->
            
</interceptor>
            
<interceptor-stack name="IpAuthority">
                
<interceptor-ref name="defaultStack"></interceptor-ref>
                
<interceptor-ref name="IpAuthorityInterceptor"></interceptor-ref>
            
</interceptor-stack>
        
</interceptors>


 

此時在你的action中加入相應的配置就可以使用該IP攔截器了。

 



柴油發電機
發電機
柴油機
柴油發電機
13636374743(上海)
13291526067(嘉興)