1.先編寫此類。
package itcast.lxd.web.simpleTagAttrib;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檔案中描述一下這個標籤
<?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.simpleTagAttrib.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我使用此標籤
<%@ 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>