做个图片的防盗链

目的是,网站本身的图片不防盗链,用户上传的图片不许外链

用户上传的图片都在userfile目录和其子目录下面

[color=blue][size=large]1. 配置filter[/size][/color]

<filter>
<filter-name>jpgServlet</filter-name>
<filter-class>
com.djwl.core.filter.JpgFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>jpgServlet</filter-name>
<url-pattern>/userfile/*</url-pattern>
</filter-mapping>



[color=blue][size=large]2. Filter[/size][/color]

package com.djwl.core.filter;

import java.io.IOException;

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;

/**
* Description: <br>
* 2010-4-13
* @author huxiao kskr@qq.com
*/
public class JpgFilter implements Filter {

@Override
public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletrequest;
HttpServletResponse response = (HttpServletResponse)servletresponse;

//获取请求来源
String linkFrom = request.getHeader("referer");

/**
* 如果不是从本网站链接,则返回本网站的logo,否则正常走
* 注意:这里的linkFrom为null的话也正常走。原因是,用户如果直接输入图片地址的话,linkFrom为null
*/
if(linkFrom != null && !linkFrom.contains(request.getServerName())){
System.out.println("盗链来自: "+linkFrom);
request.getRequestDispatcher("/images/logo_red.jpg").forward(request, response);
}else {
filterchain.doFilter(request, response);
}
}

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

}

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

}

}





[color=blue][size=large]3. 测试[/size][/color]

图片所在的是localhost1:1111,现在我用localhost1和localhost2去请求,ok的话,前者能显示,后者显示logo

body部分:这里我放了两个图片,前面一个是/images目录下的,不做防盗链,后面的做防盗链

<img src="http://localhost1:1111/images/bq_bgGreen.jpg">
<img src="http://localhost1:1111/userfile/20100405/7ef5d05bacd840e8beb8147653ad2906_81_81.jpg" />




[img]http://dl.iteye.com/upload/attachment/233443/20d30b87-dd87-3089-893c-425d113e16ea.jpg[/img]

[img]http://dl.iteye.com/upload/attachment/233444/accb9e60-b9ef-3702-bca9-a865d45819ed.jpg[/img]

OK,这就达到咱们的目的了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值