WEB优化(持续更新)

1:request.getRemoteAddr()和request.getRemoteHost()获取客户端的ip和host性能差异:
建议直接使用request.getRemoteAddr()
https://blog.csdn.net/eleven204/article/details/6625701
如果一定使用getRemoteHost:可以设置tomcat连接器(connector)的enableLookups:
为true时通过dns查询返回实际主机名称,设置为false直接返回客户端ip

2:原生ajax缓存:通过get获取数据时,当参数及url一致时会启用缓存。
需要设置头部信息禁止缓存,但是注意顺序,先open再设置。

对于jquery的ajax:cache属性设置为false即可。
其他方式:url加上时间戳作为参数,保证每次访问的url不一致即可。

3:通过反向代理(例如nginx)访问服务器时,无法直接通过request获取客户端的真实ip,此时的访问ip轨迹在请求头的x-forwarded-for中存放,通过逗号分隔。
推荐:直接使用RemoteIpFilter,该过滤器会自动解析该请求头并将原始ip和host替换到request中去。

clientip经过proxy1,proxy2,proxy3访问server,此时server接收到的x-forwarded-for中存在clientip,proxy1,proxy2,而proxy3的ip存放在remoteAddr中。
需要取得真正的ip时,可以直接做分隔取第一个。
不使用filter的写法(不推荐)
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}

注意:x-forwarded-for易于伪造,需要谨慎使用。
并且,在使用到负载均衡时,RemoteAddrFilter和RemoteHostFilter需要结合该filter使用,否则无法正确限制访问的客户端。这两个过滤器 支持使用正则表达式限制客户端的ip和host

猜你喜欢

转载自www.cnblogs.com/ForsakenCoder/p/10507830.html