日期:2014-05-16  浏览次数:20329 次

jsp自定义标签--->张国亮总结心得第四季

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

盗链是指服务提供商自己不提供服务的内容,通过技术手段绕过其它有利益的最终用户界面(如广告),直接在自己的网站上向最终用户提供其它服务提供商的服务内容,骗取最终用户的浏览和点击率。受益者不提供资源或提供很少的资源,而真正的服务提供商却得不到任何的收益。

解决途径之一——限制引用页

这种防盗链原理是,服务器获取用户提交信息的网站地址,然后和真正的服务端的地址相比较,如果一致则表明是站内提交,或者为自己信任的站点提交,否则视为盗链。

目标:要开发的标签

<class3g:referer site="http://drinkeye:8080" page="/index.jsp"/>

site:受信任站点,只允许次站点的请求

page:正确的链接页面,发现盗链后将其自动转入此页面

步骤

1) 标签处理类

<span style="font-size:16px;">public void doTag() throws JspException, IOException {

PageContext pageContext = (PageContext) this.getJspContext();

HttpServletRequest request =

(HttpServletRequest) pageContext.getRequest();

HttpServletResponse response =

(HttpServletResponse) pageContext.getResponse();

String referer = request.getHeader("referer");

System.out.println(request.getContextPath());

if(referer==null | !referer.startsWith(site)){

//判断是否盗链

</span>

<span style="font-size:16px;"> //根据page属性值,讲链接重定向指访问被盗链内容的正确页面

String contextPath = request.getContextPath();

if(page.startsWith(contextPath)){

response.sendRedirect(page);

}else if(page.startsWith("/")){

response.sendRedirect(contextPath + page);

}else{

response.sendRedirect(contextPath + "/" + page);

}

throw new SkipPageException();

}

}

</span>

2) 描述文件

3) 在内容页面使用标签

2、标签案例-<c:if>标签

标签功能:

<span style="font-size:16px;"><class3g:if exp="${psw==null }">

user == null <br>

</class3g:if>

<%

session.setAttribute("user","Tom");

%>

<class3g:if exp="${user!=null }">

user != null <br>

</class3g:if>

</span>

处理类

<span style="font-size:16px;">public class MyIfTag extends SimpleTagSupport {

private boolean exp;

public void setExp(boolean exp) {

this.exp = exp;

}

public void doTag() throws JspException, IOException {

if(exp){

JspFragment jf = this.getJspBody();

jf.invoke(null);

}

}

}

</span>

3、标签案例if else 标签

<span style="font-size:16px;"><class3g:choose >

<class3g:when exp="${user!=null }">

aaaaaaaaaa

</class3g:when>

<class3g:otherwise>

bbbbbbbbbbbbbbb

</class3g:otherwise>

</class3g:choose>

</span>

步骤:

l 编写choose标签,无属性,但有一个成员invoked,要为其编写setter和getter方法,注意doTag中需要输出标签体

l 编写子标签when标签,有boolean属性exp,

l 编写子标签otherwise标签,无属性,无成员变量