在JSP中使用自定义标签防止盗链(传智播客学习笔记)
1.先编写此类。
[java]
package itcast.lxd.web.易做图TagAttrib;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.SkipPageException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class referDemo extends SimpleTagSupport
{
String webSiteReferer ;
String webIndex;
public void setWebSiteReferer(String webSiteReferer)
{
this.webSiteReferer = webSiteReferer;
}
public void setWebIndex(String webIndex)
{
this.webIndex = webIndex;
}
public void doTag() throws JspException, IOException
{
PageContext pageContext =(PageContext)this.getJspContext();
HttpServletRequest request =(HttpServletRequest)pageContext.getRequest();
HttpServletResponse response =(HttpServletResponse)pageContext.getResponse();
if(request.getHeader("referer")==null||!request.getHeader("referer").startsWith(webSiteReferer))
{
response.sendRedirect(webIndex);
throw new SkipPageException();
}
else
{
}
}
}
这个标签带两个属性,一个是site也就是这个防盗链需要来自什么地方的连接才能够访问,第二个page的意思是如果是其他位置访问本页面需要跳转到哪里去。
JspContext必须转型为pageContext才能获得需要的几个对象,然后根据浏览器带过来的referer头就可以知道访问位置,然后对于标签的友好型,还可以自己设置输入格式,下面需要在tld文件中描述一下这个标签
[html]
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>refererTest</short-name>
<uri>http://www.itcast.lxd.com.referer</uri>
<display-name>JSTL core</display-name>
<description>JSTL 1.0 core library</description>
<tag>
<name>referExample</name>
<tag-class>itcast.lxd.web.易做图TagAttrib.referDemo</tag-class>
<body-content>empty</body-content>
<attribute>
<name>webSiteReferer</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>webIndex</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3.0我使用此标签
[html]
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.itcast.lxd.com.referer" prefix="referTest" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<referTest:referExample webSiteReferer="http://localhost" webIndex="http://www.baidu.com"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'refertest.jsp' starting page</title>
</head>
<body>
This is my JSP page. <br>
<font color="red" size="7">
这里是我的隐私日记啊,可以防盗链啊,你们一般人看不到啊 嘎嘎嘎嘎
</font>
</body>
</html>
补充:Web开发 , Jsp ,