// 一個(gè)IP,是一個(gè)32位無符號(hào)的二進(jìn)制數(shù)。故用long的低32表示無符號(hào)32位二進(jìn)制數(shù)。
柴油發(fā)電機(jī)
發(fā)電機(jī)
柴油機(jī)
柴油發(fā)電機(jī)
13636374743(上海)
13291526067(嘉興)
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相應(yīng)的action中編寫如下判斷是否用戶是校內(nèi)用戶的方法(方法參數(shù)中ip1的IP大小應(yīng)該大于ip2的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;
}
public void isSchoolUser(String ip1, String ip2) throws Exception {
// 得到用戶的IP地址
String s = ServletActionContext.getRequest().getRemoteAddr();
long l = getIP(InetAddress.getByName(s));
// 設(shè)置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");
}
}
// 得到用戶的IP地址
String s = ServletActionContext.getRequest().getRemoteAddr();
long l = getIP(InetAddress.getByName(s));
// 設(shè)置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", "你是外網(wǎng)用戶無法訪問此資源");
return "error";
}
}
}
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", "你是外網(wǎng)用戶無法訪問此資源");
return "error";
}
}
}
最后當(dāng)然是配置IP攔截器,讓它為你工作吧:
interceptors>
<interceptor name="IpAuthorityInterceptor"
class="web.IpAuthorityInterceptor">
<!--此class對(duì)應(yīng)你項(xiàng)目中的IpAuthorityInterceptor的編寫位置-->
</interceptor>
<interceptor-stack name="IpAuthority">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="IpAuthorityInterceptor"></interceptor-ref>
</interceptor-stack>
</interceptors>
<interceptor name="IpAuthorityInterceptor"
class="web.IpAuthorityInterceptor">
<!--此class對(duì)應(yīng)你項(xiàng)目中的IpAuthorityInterceptor的編寫位置-->
</interceptor>
<interceptor-stack name="IpAuthority">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="IpAuthorityInterceptor"></interceptor-ref>
</interceptor-stack>
</interceptors>
柴油發(fā)電機(jī)
發(fā)電機(jī)
柴油機(jī)
柴油發(fā)電機(jī)
13636374743(上海)
13291526067(嘉興)