java自定义 注解 annotation、标签库tag、监听listener、junit简单测试代码
完整项目和相关文档教程请免费下载: http://download.csdn.net/detail/liangrui1988/6971229
package org.rui.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*
1.2、@Target:定义注解的作用目标
@Target 用于描述注解的使用范围(即:被描述的注解可以用在什么地方),其取值有:
取值 描述
CONSTRUCTOR 用于描述构造器。
FIELD 用于描述域。
LOCAL_VARIABLE 用于描述局部变量。
METHOD 用于描述方法。
PACKAGE 用于描述包。
PARAMETER 用于描述参数。
TYPE 用于描述类或接口(甚至 enum )。
------------------------------------------------------------------------
1.1、@Retention: 定义注解的保留策略
@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Retention 用于描述注解的生命周期(即:被描述的注解在什么范围内有效),其取值有:
取值 描述
SOURCE 在源文件中有效(即源文件保留,领盒饭)。
CLASS 在 class 文件中有效(即 class 保留,领盒饭)。
RUNTIME 在运行时有效(即运行时保留)。
1.3、@Document:说明该注解将被包含在javadoc中
1.4、@Inherited:说明子类可以继承父类中的该注解
* @author Administrator
*
*/
//定义注解
//@Inherited
@Documented
@Target({ElementType.TYPE,ElementType.METHOD})//这个注解可以是类注解,也可以是方法的注解
@Retention(RetentionPolicy.RUNTIME)//定义的这个注解是注解会在class字节码文件中存在,在运行时可以通过反射获取到
public @interface myAnnotation
{
public enum ytsType{util,entity,service,mode};
public ytsType classType()default ytsType.util;
}
package org.rui.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnn2 {
String strValue() default "hello";
String[] arrayValue() default "wrold";
myEnum myEnumType() default myEnum.A;
enum myEnum{A,B,C,D} ;
}
/* enum myEnum{
A,B,C,D
}*/
package org.rui.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface HelloWorld {
public String name() default "";
}
package org.rui.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.rui.annotation.MyAnn2.myEnum;
/**
*
* @author liangrui
* Q:1067165280
*
*/
public class TestMyAnn2 {
//eunmValue=myEnum.A
@MyAnn2(strValue="hello joy",myEnumType=myEnum.B,arrayValue={"O","P","Q"})
//@Deprecated
public static void execute(){
System.out.println("test annotation2");
}
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//读取注解上面的信息
//MyAnn2 ann2=new MyAnn2();
Class<TestMyAnn2> clazz=TestMyAnn2.class;
Method method=clazz.getMethod("execute",new Class[]{});
System.out.println(method.getName());
//判断该方法是否包含MyAnnotation注解
if(method.isAnnotationPresent(MyAnn2.class)){
System.out.println("true");
//获取方法上的注解
MyAnn2 ann2=method.getAnnotation(MyAnn2.class);
System.out.println("strValue:"+ann2.strValue());
System.out.println("eunmVal:"+ann2.myEnumType());
for(String str:ann2.arrayValue()){
System.out.println("arrayVal:"+str);
}
}
//执行方法
method.invoke(new TestMyAnn2(), new Object[]{});
Annotation[] an=method.getAnnotations();
System.out.println(an.length+" "+an[0]);
}
}
package org.rui.annotation;
import java.lang.reflect.InvocationTargetException;
public class Test {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException, InstantiationException {
//java的反射机制 解析注解
ParseAnnotation parse = new ParseAnnotation();
parse.parseMethod(SayHello.class);
parse.parseType(SayHello.class);
}
}
package org.rui.annotation;
import org.rui.annotation.myAnnotation.ytsType;
@myAnnotation(classType=ytsType.util)
public class SayHello {
public static void main(String[] args) {
SayHello t=new SayHello();
t.testHello(null);
}
@HelloWorld(name="林冲")
@myAnnotation
public void testHello(String name){
if(name==null||"".equals(name)){
System.out.println("hello wrold");
}else{
System.out.println(name+" say: hello wrold");
}
}
}
package org.rui.annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.rui.annotation.myAnnotation.ytsType;
public class ParseAnnotation {
public void parseMethod(Class clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException, InstantiationException{
Object obj = clazz.getConstructor(new Class[]{}).newInstance(new Object[]{});
for(Method method : clazz.getDeclaredMethods()){//获取类方法
//通过类字节码 获得方法上面的注解实列
HelloWorld say = method.getAnnotation(HelloWorld.class);
String name = "";
if(say != null){
//获得注解参数
name = say.name();
//执行clazz类上面的 方法
method.invoke(obj, name);
}
//通过类字节码 获得方法上面的注解实列
myAnnotation myAn = (myAnnotation)method.getAnnotation(myAnnotation.class);
if(myAn != null){
if(ytsType.util.equals(myAn.classType())){
System.out.println("myAn.classType() 默认的值 ytsType枚举中的 util");
}else{
System.out.println("this is a other method");
}
}
}
}
@SuppressWarnings("unchecked")
public void parseType(Class clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
//通过类字节码 获得这个类上面的注解实列
myAnnotation myAn = (myAnnotation) clazz.getAnnotation(myAnnotation.class);
if(myAn != null){
if(ytsType.util.equals(myAn.classType())){
System.out.println("myAn.classType() 默认的值 ytsType枚举中的 util");
// System.out.println("this is a util class");
}else{
System.out.println("this is a other class");
}
}
}
}
==========================listener====================================
package org.rui.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ReplyListener implements ServletContextListener {
private ReplyTime replyTime=null;
@Override
public void contextDestroyed(ServletContextEvent event) {
String status="sys replyListener stop--------------";
event.getServletContext().log(status);
replyTime=new ReplyTime(5000);
System.out.println(status);
if(replyTime!=null){
replyTime.stop();
}
}
@Override
public void contextInitialized(ServletContextEvent event) {
String status="sys replyListener star--------------";
event.getServletContext().log(status);
replyTime=new ReplyTime(5000);
System.out.println(status);
replyTime.start();
}
}
package org.rui.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ListTest implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("simple Listener Test destroyed #################");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("simple Listener Test init start#################");
}
}
package org.rui.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* [接收事件] HttpSessionEvent
[触发场景] 在session (HttpSession)对象建立或被消灭时,会分别呼叫这两个方法。
*
*
*/
public class SessionListener implements HttpSessionListener {
//private final static Logger logger = Logger.getLogger(SessionListener.class);
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
//logger.debug("session创建成功,id=" + arg0.getSession().getId());
System.out.println("做一些session 连接成功的相关操作! 如用户登陆.....");
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
String cookid=(String) arg0.getSession().getAttribute("COOKIEID");
System.out.println("做一些用户登出的相关操作");
}
}
package org.rui.listener;
import java.util.Date;
import java.util.Timer;
public class ReplyTime {
private final Timer timer =new Timer();
private final int min;
public ReplyTime(int minutes){
this.min=minutes;
}
public void start(){
Date date=new Date();
timer.schedule(new Replytask(), date,min);
}
public void stop(){
timer.cancel();
}
}
package org.rui.listener;
import java.util.Date;
import java.util.TimerTask;
public class Replytask extends TimerTask {
@Override
public void run() {
System.out.println("[SYSTEM]: SMS reply listener run 当前时间:======="+ new Date()+"=======");
}
}
======================tag=============================
package org.rui.tag;
import java.io.IOException;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class TagExample extends BodyTagSupport {
int counts;//counts为迭代的次数。
public TagExample()
{super(); }
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}
@Override
public int doEndTag() throws JspException {
try {
pageContext.getOut().print("hello wrold...现在的时间是:"+new Date());
} catch (IOException e) {
e.printStackTrace();
}
return EVAL_PAGE;
}
}
package org.rui.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
public class HelloWorldSimpleTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
getJspContext().getOut().write( "<table border=1><tr bgcolor=9944cc><td>simpeltag测试</tr></td><tr tr=cc44cc><td>helloWorld!</td></tr></table>" );
}
}
package org.rui.tag;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.Hashtable;
import java.io.Writer;
import java.io.IOException;
import java.util.Date;
/**
*演示怎么实现Tag接口的方式来开发标签程序
*/
public class HelloTag_Interface implements javax.servlet.jsp.tagext.Tag
{
private PageContext pageContext;
private Tag parent;
public HelloTag_Interface()
{
super();
}
/**
*设置标签的页面的上下文
*/
public void setPageContext(final javax.servlet.jsp.PageContext pageContext)
{this.pageContext=pageContext;
}
/**
*设置上一级标签
*/
public void setParent(final javax.servlet.jsp.tagext.Tag parent)
{
this.parent=parent;
}
/**
*开始标签时的操作
*/
public int doStartTag() throws javax.servlet.jsp.JspTagException
{
return SKIP_BODY; //返回SKIP_BODY,表示不计算标签体
}
/**
*结束标签时的操作
*/
public int doEndTag() throws javax.servlet.jsp.JspTagException
{
try
{
pageContext.getOut().write("Hello World!你好,世界!");
}
catch(java.io.IOException e)
{
throw new JspTagException("IO Error: " + e.getMessage());
}
return EVAL_PAGE;
}
/**
*release用于释放标签程序占用的资源,比如使用了数据库,那么应该关闭这个连接。
*/
public void release() {}
public javax.servlet.jsp.tagext.Tag getParent()
{
return parent;
}
}
package org.rui.tag;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.Hashtable;
import java.io.Writer;
import java.io.IOException;
public class BodyTagExample extends BodyTagSupport{
int counts;//counts为迭代的次数。
public BodyTagExample()
{ super(); }
/**
*设置counts属性。这个方法由容器自动调用。
*/
public void setCounts(int c)
{ this.counts=c; }
/**
*覆盖doStartTag方法
*当返回EVAL_BODY_INCLUDE时,就计算标签的Body,
*如果返回SKIP_BODY,就不计算标签的Body。
*/
public int doStartTag() throws JspTagException {
System.out.println("doStartTag==========");
if(counts>0){//表示继续计算一次BodyTag
return EVAL_BODY_TAG;
}else
{//不计算标签的Body
return SKIP_BODY;
}
}
/**
*覆盖doAfterBody方法
*如果返回EVAL_BODY_TAG,表示继续计算一次BodyTag,
*直接返回SKIP_BODY才继续执行doEndTag方法。
*/
public int doAfterBody() throws JspTagException{
System.out.println("doAfterBody"+counts);
if(counts>1){
counts--;
//System.out.println("EVAL_BODY_TAG:"+EVAL_BODY_TAG);
return EVAL_BODY_TAG;
} else {
//System.out.println("SKIP_BODY:"+SKIP_BODY);
return SKIP_BODY;
}
}
/**
*覆盖doEndTag方法
*/
public int doEndTag() throws JspTagException{
System.out.println("doEndTag");
try {
if(bodyContent != null){
bodyContent.writeOut(bodyContent.getEnclosingWriter());
}
} catch (IOException e) {
e.printStackTrace();
}
return EVAL_PAGE;
}
public void doInitBody() throws JspTagException{
System.out.println("doInitBody");
}
public void setBodyContent(BodyContent bodyContent)
{
System.out.println("setBodyContent");
this.bodyContent=bodyContent;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 自定义村签 -->
<jsp-config>
<taglib>
<taglib-uri>/demotag</taglib-uri>
<taglib-location>/WEB-INF/tagTest.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/hello/rui</taglib-uri>
<taglib-location>/WEB-INF/myTag.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/bodyTag/rui</taglib-uri>
<taglib-location>/WEB-INF/bodyTag.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/itertor/rui</taglib-uri>
<taglib-location>/WEB-INF/itertor.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/simple/rui</taglib-uri>
<taglib-location>/WEB-INF/simple.tld</taglib-location>
</taglib>
</jsp-config>
<!--
[接收事件] ServletContextEvent
[触发场景] 在Container加载Web应用程序时(例如启动 Container之后),
会呼叫contextInitialized(),
而当容器移除Web应用程序时,会呼叫contextDestroyed ()方法。
-->
<listener>
<listener-class>org.rui.listener.ListTest</listener-class>
</listener>
<!--
[接收事件] HttpSessionEvent
[触发场景] 在session (HttpSession)对象建立或被消灭时,会分别呼叫这两个方法。
-->
<listener>
<listener-class>org.rui.listener.SessionListener</listener-class>
</listener>
<listener>
<listener-class>org.rui.listener.ReplyListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
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>bodyTagExamples</short-name>
<uri>/bodyTag/rui</uri>
<tag>
<name>bodyTagTest</name>
<tag-class>org.rui.tag.BodyTagExample</tag-class>
<body-content>jsp</body-content>
<attribute>
<name>counts</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>examples</short-name>
<uri>/demotag</uri>
<tag>
<name>hello_int</name>
<tag-class>org.rui.tag.HelloTag_Interface</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
<?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>simpleExample</short-name>
<uri>/simple/rui</uri>
<tag>
<name>helloWorld</name>
<tag-class>org.rui.tag.HelloWorldSimpleTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<!-- <short-name>examples</short-name>
<uri>/hello/rui</uri> -->
<tag>
<name>hello</name>
<tag-class>org.rui.tag.TagExample</tag-class>
</tag>
</taglib>
jsp=====
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/demotag" prefix="hello"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'demo.jsp' starting page</title>
</head>
<body>
<h1>以下是自定义tag显示的内容:</h1>
<p><hello:hello_int/></p>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/bodyTag/rui" prefix="bt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>以下是自定义tag显示的内容:</h1>
<bt:bodyTagTest counts="5" >
<p>
现在的时间是:<%= new java.util.Date()%>
</p>
</bt:bodyTagTest>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/hello/rui" prefix="he"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'bodyTag.jsp' starting page</title>
</head>
<body>
<h2>自定义标签 extends TagSupport实现</h2>
<he:hello/>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/simple/rui" prefix="sim" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>simple Tag 输出测试</h2>
<sim:helloWorld/>
</body>
</html>
======================
太多了,请下载项目源码吧,里面有相关教程文档,免费下载