首页 > 代码库 > 标签案例-开发防盗链标签

标签案例-开发防盗链标签

 1 package cn.itcast.web.tag; 2  3 import java.io.IOException; 4  5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import javax.servlet.jsp.JspException; 8 import javax.servlet.jsp.PageContext; 9 import javax.servlet.jsp.SkipPageException;10 import javax.servlet.jsp.tagext.SimpleTagSupport;11 12 public class RefererTag extends SimpleTagSupport {13 14     private String site;15     private String page;16 17     public void setSite(String site) {18         this.site = site;19     }20 21     public void setPage(String page) {22         this.page = page;23     }24 25     @Override26     public void doTag() throws JspException, IOException {27     28         PageContext pageContext = (PageContext) this.getJspContext();29         HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();30         HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();31         32         //1.得到来访者referer33         String referer = request.getHeader("referer");34         if(referer==null||!referer.startsWith(site)){35             if(page.startsWith(request.getContextPath())){36                 response.sendRedirect(page);37             }else if(page.startsWith("/")){38                 response.sendRedirect(request.getContextPath()+page);39             }else{40                 response.sendRedirect(request.getContextPath()+"/"+page);41             }42             43             throw new SkipPageException();44         }45         46     }47     48     49 50 }
RefererTag

<e:referer site="http://localhost" page="index.jsp"></e:referer>