My favorites | Sign in
t-2
Project Home Downloads Wiki Issues Source
READ-ONLY: This project has been archived. For more information see this post.
Search
for
Annotation  

ja , en
Updated Mar 6, 2010 by shinpei.ohtani@gmail.com

Annotation for T2 framework.

Annotation

How to use annotations?

Since Java5, there is the annotation technology for enhancing class, method, field, even parameter. Annotation is powerful and simple mechanism to provide some information in the source code which can be used by compiler, frameworks, or applications.

With T2 framework, there are mainly 3 annotation types which is using:type annotation, method annotation, and parameter annotation. Type annotation is enhanced at a class, which mainly means this class has a feature that effects whole this class. Method annotation effects a method and it is mainly used by T2. Parameter annotation is kind of support type annotation for invoking method by T2.In some case, you might use it, others you are not going to use.

Annotations listed below are T2 framework specific annotations.

Type annotations

@Page

@Page is the annotation to tell T2 framework that this class is page class, a class of matching to a url. T2 framework can find and invoke page class only.

Attribute

  • value
    • Specify the url which you want to invoke this page.If not specified, simple class name(Hoge -> hoge) is used.

Sample

This class is accessed by http://yourdomain/your-context-root/hello.
@Page("/hello")
public class HelloPage {
	......
}

@ForwardTo

@ForwardTo is a support annotation telling where to transit for forwarding with page class. This annotation is only used when the navigation method is Forward.to(Class).

Attribute

  • value
    • Specify where to transit.

Method annotations

@GET

@GET is a method annotation telling the annotated method is invoked by only HTTP GET.

@POST

@POST is a method annotation telling the annotated method is invoked by only HTTP POST.

@PUT

@PUT is a method annotation telling the annotated method is invoked by only HTTP PUT.

@DELETE

@DELETE is a method annotation telling the annotated method is invoked by only HTTP DELETE.

@HEAD

@HEAD is a method annotation telling the annotated method is invoked by only HTTP HEAD.

@OPTIONS

@OPTIONS is a method annotation telling the annotated method is invoked by only HTTP OPTIONS.

@ActionPath

@ActionPath is a method annotation having url matching feature. With @ActionPath, invoking the annotated method when requested url is matched with @ActionPath#value(). You can separate action methods by url using @ActionPath.

Attribute

  • value
    • The url which can invoke this action method.If none of specified, method name is used as the url.

Sample

@Page("/hello")
public class HelloPage {

	//requested from http://yourdomain/your-context-root/hello/request
	@ActionPath
	public Navigation request(HttpServletRequest request) {
		...
	}
	
	//requested from http://yourdomain/your-context-root/hello/struts
	@ActionPath("struts")
	public Navigation likeStrutsType(HttpServletRequest request,
			HttpServletResponse response) {
		...
	}

@ActionParam

@ActionParam is a method annotation having request parameter matching feature. Simply to say, you can separate each action method by user pushed button.

Restriction

  • @ActionParam can not be used with @Ajax.

Attribute

  • value
    • Request parameter name.If none of specified, use method name as request parameter name.

Sample

The jsp is like this.
<form name="addForm" action="${t:url('/add')}" method="post">
	<input type="submit" name="add" value="Display result!"/>
	...
The page and @ActionParam is this:
@Page("/add")
public class AddPage {

	//This method should be invoked when request parameter "add" come.
	@POST
	@ActionParam
	public Navigation add(WebContext context) {
		...
	}

@Default

@Default is the annotation telling the annotated method is the default method when there are no other methods invoking. You better set @Default method each Page class.

Attribute

There is no attribute for @Default.

Sample

@Page("/hello")
public class HelloPage {

    //This method is the default invocation method for this page class.
	@Default
	public Navigation index(Request request) {
		request.setAttribute("greet", helloService.hello());
		return Forward.to("/jsp/hello.jsp");
	}

@Ajax

@Ajax is the annotation telling that the annotated method is invoked when the request type is xmlhttprequest. So how T2 framework know a request is xmlhttprequest or not?The conditions are:
+ the request header "X-Request-With" must exist. + the value of "X-Request-With" must be "xmlhttpreques" in case insensitive manner.
The modernized javascript framework like these below set X-Request-With as a good manner.
+ Prototype.js + jQuery + ExtJs

Attribute

  • value
    • not used.

Sample

@Page("/ajaxJQuery")
public class AjaxJQueryPage {

	@Ajax
	@POST
	public Navigation execute(WebContext context) {
		String hoge = context.getRequest().getAttribute("hoge");
		return Json.convert(hoge + " is jQuery.");
	}

}

@Amf

FlexまたはAIRからAMFを使った高速バイナリ通信で呼ぶアクションメソッドを指定するアノテーションです. @Amfを使うと、@Pageの値がFlexで言うところのdestination、@Amfの値が呼び出しFunction名になります. Flexの呼び出しの詳細はRemoteObjectを参照してください.

属性

  • value
    • Flexからの呼び出し名を指定します.

サンプル

Flex側の簡単な呼び出しは以下のようになります.

  • ex. mxml
  • <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" height="600" width="800">
      <mx:Script>
        <![CDATA[
          private var ro:RemoteObject;
          public function callAmf():void{
            if(ro == null){
              ro = new RemoteObject("amfsimple1");
              var endPoint:String = URLUtil.getFullURL(Application.application.url, "t2.amf");
              var channel:Channel = URLUtil.isHttpsURL(endPoint) ?
                new SecureAMFChannel(null,endPoint) : new AMFChannel(null, endPoint);
              var channelSet:ChannelSet = new ChannelSet();
              channelSet.addChannel(channel);
              ro.channelSet = channelSet;
            }
            var token:AsyncToken = ro.execute(data);
            token.addResponder(new AsyncResponder(
              function(e:ResultEvent, o:Object=null):void{
                Alert.show("success");
              },
              function(e:FaultEvent, o:Object=null):void{
                Alert.show("fail:" + e.message);
              }
            ));
          }
        ]]>
      </mx:Script>
      <mx:Button label="Call" width="200" buttonMode="true" useHandCursor="true" click="callAmf()" />
    </mx:Application>
  • ex.Page class
  • @Page("/amfsimple1")
    public class AjaxJQueryPage {
    
    	@Amf
    	@Default
    	public Navigation execute(WebContext context) {
    	......
    	}
    
    }

parameter annotation

引数アノテーションは、T2から引数にコンポーネントをインジェクトしてもらうためのサポート用のアノテーションです. T2では、主に型で引数インジェクトしてもらうのが主流のスタイルですが、状況によっては明示的にユーザが特定の型・特定の値を 指定する必要があります.このような場合に引数アノテーションを使います.

@Form

@Formは送信されてきたフォームの内容をPOJOに変換するための引数アノテーションです. POJOへの型変換はT2が行います.

属性

  • resolverClass
    • FormをPOJOへ変換するためのリゾルバクラスを指定する.デフォルトは、org.t2framework.t2.spi.impl.FormResolverImpl

サンプル

	@POST
	@ActionParam
	public Navigation addWithForm(@Form AddForm dto, ErrorInfo errorInfo) {
		......
	}

参考

デフォルトの挙動では、リゾルバクラスで変換した際に発生したエラーはErrorInfoにストアされます. 引数にErrorInfoも同時にインジェクトするようにしておけば、T2フレームワークが変換した際にエラーが発生したかどうかを知ることが出来ます.
ベストプラクティスの@Formを使って変換する場合には、ErrorInfoも引数に記載するを参照してください.

@RequestHeader

@RequestHeaderはリクエストヘッダを取得する引数アノテーションです.

属性

  • key
    • リクエストヘッダのキーを指定します.指定しない場合、リクエストヘッダを全て取得して返します(以下、制約参照).

制約

@RequestHeaderは以下の型をサポートしています.
  • String
    • ヘッダのある特定のキー項目に該当するヘッダ情報
  • Stringの配列
    • ヘッダのある特定のキー項目に該当する複数のヘッダ情報
  • Map
    • ヘッダ情報全て

サンプル

@Page("/requestheader")
public class RequestHeaderPage {

	//リクエストヘッダ全てを取得する
	@POST
	@ActionParam
	public Navigation execute1(@RequestHeader Map<String, String> map, WebContext context) {
		......
	}

	//リクエストヘッダからcontent-typeのみ取得する
	@POST
	@ActionParam
	public Navigation execute2(@RequestHeader(key = "content-type")
	String header, WebContext context) {
		......
	}

}

@RequestParam

@RequestParamはリクエストパラメータを取得する引数アノテーションです. リクエストパラメータの特定のキーの値を取得できます.

属性

  • key
    • リクエストパラメータのキーを指定します.必須項目です.
  • empty
    • 空文字がインジェクトされるのを許可するかを指定します.デフォルトではtrueです.falseの場合、例外が発生します(後述).

制約

@RequestParamは以下の型をサポートしています.
  • String
    • パラメータのある特定のキー項目に該当するヘッダ情報
  • Stringの配列
    • パラメータのある特定のキー項目に該当する複数のヘッダ情報
empty属性がfalseの場合、以下の例外が発生します.ErrorHandlerなどで適切に処理してください.
  • RequestParameterNotFoundRuntimeException
  • InvalidRequestParameterTypeRuntimeException

サンプル

	@POST
	@ActionParam
	public Navigation message(@RequestParam("left") String left, 
		@RequestParam("right") String right, HttpServletRequest request) {
		......
	}

@SessionAttr

@SessionAttrはセッションのある特定のキーの内容を取得する引数アノテーションです.

属性

  • key
    • リクエストパラメータのキーを指定します.必須項目です.
  • nullable
    • nullがインジェクトされるのを許可するかを指定します.デフォルトではtrueです.falseの場合、例外が発生します(後述).

制約

Session内から取得したオブジェクトのクラスと、引数で指定したクラスの間に型の互換性の必要があります.

null属性がfalseの場合、以下の例外が発生します.ErrorHandlerなどで適切に処理してください.
  • SessionAttributeNotFoundRuntimeException
  • InvalidSessionAttributeTypeRuntimeException

サンプル

	@POST
	@ActionParam
	public Navigation message(@SessionAttr("hoge") String hoge, 
		@SessionAttr("no_such_attr") String nosuchAttr, WebContext context) {
		......
	}

@Index

@IndexはForEach内のサブミットされたボタンの何番目かを取得するためのアノテーションです.

属性

  • value
    • 評価式のキー名です.デフォルトではindexで、ほとんどのケースで変更する必要はありません.

制約

  • @Indexはリクエストパラメータのキーから解析するため@ActionParamと併用する必要があります.
  • インデックスはhoge[0]のような形式である必要があります(下記jspを参考にしてください).

サンプル

jsp
	<c:forEach var="e" items="${hogeList}" varStatus="s">
		<input type="submit" name="hoge[${s.index}]" value="${e}"/>
		<br />
	</c:forEach>
Pageクラス
	@POST
	@ActionParam("hoge[{index}]")
	public Navigation hoge(@Index int id) {
		......
	}

@Var

@Pageや@ActionPathに書かれたURLの断片を取得するためのアノテーションです. T2の評価式を使って解釈します.
RESTライクな形式でアクセスされたときなどに活用できます.

属性

  • value
    • URLのキーを指定します.必須項目です.
  • nullable
    • nullがインジェクトされるのを許可するかを指定します.デフォルトではtrueです.falseの場合、例外が発生します.

Sample

Page class is like this:
@Page("/var/{aaa}/{bbb}")
public class VarPage {

	@Default
	public Navigation index(
		@Var("aaa") String str, 
		@Var("bbb") String str2) {
		......
	}

}

@Upload

Parameter annotation for uploadinf file. You might not use this annotation, and should use just UploadFile type.

Back to TOP

Powered by Google Project Hosting