Serfj Chinese Reference Manual (self-taught Edition)

Source: Internet
Author: User

Serfj Reference Manual

Directory

1. Framework
1.1 rest URLs
1.2 Standard URLs
2. Controller
2.1 controller Annotation
2.2 obtain parameters from the request
2.3 add parameters to the response
2.4 display page
3. serialization
4. Service Configuration
4.1 configure attributes
5. Resource search Style
5.1 function-oriented style
5.2 model-based function-oriented style
5.3 model-oriented style
6. Non-Web Client

1. Framework

Serfj provides an MVC Architecture, but it does not contain any model. Its main feature is to use controllers to manage rest requests through these controllers.

The Controller represents available resources in the application and sends messages to these resources through rest requests. When a request is sent to serfj
The main servlet (net. SF. serfj. restservlet), a resource (Controller) that can process this request is called and responds
Client request. This response can be a webpage, A serialized object, or HTTP status code 204 (which means there is no content ).

1.1 rest URLs

Since rest requests control the processing of the serfj application, it is important to read this section. However, these concepts are easy to explain,
So everything is easy to understand.

Serfj supports the following HTTP methods:
Get: Used to query resource information or display webpages.
POST: used to create new resources.
PUT: Used to update resources.
DELETE: Used to DELETE a resource.

For example, if the page you want to display contains a Form for updating or creating a resource, you need to send a GET request instead of a PUT request.
However, the submit button of Form (used to update resource information) will send a PUT request.

The URL template of the REST request is:

/Accounts? Query_string
/Accounts/identifier? Query_string
/Accounts/non-standar-action? Query_string
/Accounts/identifier/edit? Query_string
/Accounts/identifier/newResource? Query_string
/Accounts/identifier/non-standar-action? Query_string

Note that the resource name must be a complex number and the identifier must start with a number. But SerfJ is a URL that can parse nested resources:
PS: Nested resources determine the method of the Controller to be executed based on the last resource.

/Banks/identifier/accounts? Query_string
/Banks/identifier/accounts/identifier? Query_string
/Banks/identifier/accounts/non-standar-action? Query_string
/Banks/identifier/accounts/identifier/edit? Query_string
/Banks/identifier/accounts/identifier/newResource? Query_string
/Banks/identifier/accounts/identifier/non-standar-action? Query_string

If you use a URL with extension, the returned results will not be a webpage, but a serialized object. Therefore, according to the used extension,
You can receive JSON, XML, or serialized objects:

/Accounts. xml? Query_string
/Accounts/identifier. json? Query_string
/Accounts/non-standar-action.pdf? Query_string
/Accounts/identifier/non-standar-action.txt? Query_string

Note: The rest urls template should be in the following format:
Normal:/resource name [[. Extension] [/identifier [. Extension] [/method name [. Extension] [? Query string]
Nesting:/resource 1 Name/resource 1 identifier/resource 2 Name/resource 2 Identifier.../resource n name/resource n identifier

1.2 Standard URLs

There are some URLs that will always call the same Controller method:

HTTP Method urlcontroller's methodviewmeaning
GET/accountsindex () index shows each resource
Post/accountscreate () create a resource
GET/accounts/1 show () show a resource with ID 1
Put/accounts/1 update () Update a resource with ID 1
Delete/accounts/1 Delete () delete a resource with ID 1
GET/accounts/newresourcenewresource () New displays a form for creating resources
GET/accounts/1/editedit () EDIT displays a form to update the attributes of a resource whose ID is 1.

2. Controller

The controller is a key feature of serfj, where rest requests are distributed to them and they respond to these requests. A response may be a page, a serialized object, or nothing (such as HTTP Status Code ).

There are two ways to write a controller (more methods will be available in the next serfj version), one is to expand the net. SF. serfj. restcontroller class, and the other is to write a JavaBean.
The last case is special, because the Controller will not be able to do some actions, such as getting parameters from the request, redirecting to another web page, or sending objects to the JSP page.

Now, extending the RestController class is the best way to write a controller. Although the request to be processed does not necessarily contain parameters, the method can return an object and throw an exception.
For example, if we need a controller attendance/account requirement, we must write a class like this:

Public class Account extends RestController {
}

2.1 controller Annotation

There are several annotations that tell the controller which methods can accept which type of HTTP request.

@ GET: method for processing GET requests.
@ POST: method for processing POST requests.
@ PUT: method for processing PUT requests.
@ DELETE: The method is used to process the DELETE request.

In addition, there is a comment @ DoNotRenderPage that tells the Controller that after the method is executed, the page is not displayed, but an HTTP204 code will be answered. If the method returns an object instead of not making a page,
Then it does not need to indicate @ DoNotRenderPage. Only when the method does not return any value (the void method) and the developer does not want to render a result page, it must be noted.

2.2 obtain parameters from the request

Obviously, the class we previously wrote won't do anything, and it won't respond to any requirements. Let's write more code on this basis. If we need a method to update some account information
(PUT/account/1), we can write this method:

Public class Account extends RestController {
@ PUT
Public void updateAccount (){
String accountId = this. getId ("account ");
}
}

We can see that the getId (String) method can be called in this method to obtain the account identifier. Let's take a look at how to get other accounts in nested resources (PUT/banks/1/accounts/2 ).
User ID.

Public class Account extends RestController {
@ PUT
Public void updateAccount (){
String accountId = this. getId ("account ");
String bankId = this. getId ("bank ");
}
}

If your request contains many parameters, you can also obtain them in this method. These parameters can be either in the query string or in the Request body.

Public class Account extends RestController {
@ PUT
Public void updateAccount (){
String accountId = this. getId ("account ");
String someInfo = this. getStringParam ("some_info_param_name ");
}
}

If the sent and accepted parameters are not strings but objects, we need to serialize the objects to Base64 strings before sending them, and deserialize the objects when the parameters are received in the Controller method.
SerfJ provides a tool for serialization/deserialization between class objects and Base64 strings. You can use it wherever you need it.

Public class Account extends RestController {
Private Base64Serializer serializer = new Base64Serializer ();

@ PUT
Public void updateAccount (){
String accountId = this. getId ("account ");
String someInfo = this. getStringParam ("some_info_param_name ");
Balance balance = (Balance) serializer. deserialize (this. getStringParam ("balance "));
}
}

2.3 add parameters to the response

Now we know how to get the request parameters, but sometimes we need to send the object to a JSP, for example. Obviously, these objects must implement the java. io. Serializable interface.

Public class Account extends RestController {
@ PUT
Public void updateAccount (){
Account account = // some code to get an account
This. addObject2Request ("my_object_param_name", account );
}
}

This is a common method for returning objects. As we can see in section 1.1, these methods will be called by the expanded rest urls request with the extension name. The extension indicates what kind of framework is used.
Serialization responds to the request. SerfJ provides three different serialization extension XML, JSON or Base64 (corresponding to the extension. XML, JSON,. 64), but developers can write
Serialization extension (see section 3rd ).

For example, there are two ways to respond to URLS requests such as/accounts/1/balance. xml. Let's first look at the first one:

Public class Account extends RestController {
@ GET
Public Balance balance (){
Balance balance = new Balance ();
Return balance;
}
}

This method always tries to return an object. How to serialize the object depends on the extension used. However, we may need a method to return
When using an object, use page rendering in other cases:

Public class Account extends RestController {
@ GET
Public void balance (){
Balance balance = new Balance ();
If (response. getserializer ()! = NULL ){
Response. serialize (balance );
} Else {
// This is optional, we need it only if we want to send the object to the page
This. addobject2request ("balance", balance );
Response. renderpage ("balance ");
}
}
}

2.4 display page

After a method is executed in the controller, a page is always displayed unless the method returns an object or @ donotrenderpage is used to mark the method. The Save path of the displayed page is
Views. Directory/Resource Name/metrics name.jsp(.htmlor .htm ). The views. Directory is defined in the serfj. properties configuration file. Example:
Below:

Controller
Method View
Account
Void index () views. Directory/account/Index
Account
Void show () views. Directory/account/show
Account
Void newresource () views. Directory/account/New
Bank void edit () views. Directory/Bank/edit
Car void Update () views. Directory/CAR/update
Account
Void create () views. Directory/account/create
Account
Void Delete () views. Directory/account/delete
Account
Void mymethod () views. Directory/account/mymethod
Account
Object mymethod () returns a serialized object
Account
@ Donotrenderpage void mymethod () returns an HTTP 204 code

This is the Web page displayed by the framework by default, but other web pages can also be displayed. There are three methods:

RenderPage ():
Display default frame page
RenderPage (String pageName ):
Display views. directory/current resource name/pageName page. pageName can contain an extension. If there is no extension, you can search for a page file with a standard extension (. jsp \. html \. htm ).
RenderPage (String resourceName, String pageName ):
Display the views. directory/resourceName/pageName page. pageName can contain extensions. If there is no extension, search for page files with a standard extension (. jsp \. html \. htm ).

3. serialization

When a REST request arrives, if the part before the query string contains an extension, the framework automatically searches for specific serialization classes that can serialize the requested resources (read section 5th to learn how to search for specific serialization classes of resources ).
SerfJ provides serialization of XML, JSON, and Base64 (corresponding to. XML,. JSON, And. base64 extensions). However, developers can use custom serialization classes for different suffixes.
It is easy to develop a new serialization class. You only need to implement the net. sf. serfj. serializers. Serializer interface. You do not need to explain it more. For details, refer to its Javadoc:

Package net. sf. serfj. serializers;
 
/**
* Interface for Serializers.
*
* @ Author Eduardo
*/
Public interface Serializer {
/**
* Serialize an object as a string
*
* @ Param object
* Objects to be serialized
* @ Return object serialized string.
*/
Public String serialize (Object object );

/**
* Deserialization from a string to an object
*
* @ Param string
* Serialized string of the object
* @ Return object.
*/
Public Object deserialize (String string );

/**
* Content type is used for the response type of response.
*/
Public String getContentType ();

/**
* Returns the extension to be processed by the serialization class.
*
* @ Return indicates the extension without vertices.
*/
Public String getExtension ();
}

The name of the serialization class must start with the extension (uppercase), and the name of the resource must end with Serializer (for example, the following format ):

XmlBankSerializer: The implementation of serializing Bank resources into xml.
JsonBookSerializer: The implementation of serializing Book resources to json.
PdfBookSerializer: The implementation of serializing Book resources to pdf.

4. Service Configuration

The framework follows the Convention priority principle, so it is almost unnecessary to use it. Of course, it needs to be configured, but only a little bit. However
Users who want to get it to run better, they can set several configuration attributes to prevent SerfJ from finding some resources through speculation.

SerfJ has only one configuration file: serfj. properties in the/config directory of classpath. To get it started, you only need
You need to configure a main. package attribute. This property must point to where SerfJ will look for controllers and serializer, but it does not mean that all controllers and
Serialization must be in this software package. The framework looks for the Controller and serializer in a way that will be explained in the next section.

4.1 configure attributes

Main. package:
MAIN package name (search controller, the main basis of the serializer ). The default value is net. sf. serfj.
Views. directory:
Search for the Directory of the web page. The default value is views under the web root directory.
Package. style:
Framework.
There are four possible values: FUNCTIONAL/functional, FUNCTIONAL_BY_MODEL/functional_by_model, MODEL/model or OFF.
If the value is OFF, this attribute is not defined.
Alias. controllers. package:
The alias of the controller package.
When package. style is FUNCTIONAL and FUNCTIONAL_BY_MODEL, append this name to the value of main. package and use it as the controller package name. The default value is controllers.
Alias. serializers. package:
The alias of the serializer package.
When package. style is FUNCTIONAL and FUNCTIONAL_BY_MODEL, append this name to the main. package property value and use it as the serializer package name. The default value is serializers.
Suffix. controllers:
The additional suffix of the controller class name. The default value is off, so no suffix is used.
Suffix. serializers:
The additional suffix of the serializer class name. The default value is off, so no suffix is used.

5. Resource search Style

There are three SerfJ resource search methods:

Functional.
Functional by model.
By Model.

If no method is defined in the configuration file, the framework uses three methods to search resources in sequence. This attribute must be defined if developers want to determine whether Serfj uses a certain search method.

5.1 function-oriented style

If you are looking for a controller, the limited name of the controller class should be:

Main. package + "." + alias. controllers. package + "." + capitalized (singularized (resource name) + suffix. controllers.

If the following configuration environment is available:

Main. package: net. sf. serfj. tests
Alias. controllers. package not defined. The default value is controllers.
Suffix. controllers: Ctrl
Resource: banks

The framework looks for a controller with the following name:

Net. sf. serfj. tests. controllers. BankCtrl

If the searched resource is a serializer, the class name uses the prefix. However, this prefix cannot be configured. It is fixed that the first letter of the extension name is capitalized as the prefix. For example, this configuration is available:

Main. package: net. sf. serfj. tests
Alias. serializers. package this attribute is not defined. The default value is serializers.
Suffix. serializers: This attribute is not defined. The default value is Serializer.

Search for the JSON serializer class of an account resource. The fully qualified name of this class will be:

Net. sf. serfj. tests. serializers. JsonAccountSerializer

5.2 model-based function-oriented style

In this policy, after the Resource Name is singular, the attached main. package name is used. If you search for a controller class, its fully qualified class name is as follows:

Main. package + ". "+ singularized (resource name) + ". "+ alias. controllers. package + ". "+ capitalized (singularized (resource name) + suffix. controllers.

If the following configuration attributes are defined:

Main. package: net. sf. serfj. tests
Alias. controllers. package: ctrl
Suffix. controllers: This attribute is not defined. The default value is a null string.
Resource: banks

The framework will search for controller classes with the following qualified names:

Net. sf. serfj. tests. bank. ctrl. Bank

If the searched resource is a serializer, the class name uses the prefix. However, this prefix cannot be configured. It is fixed that the first letter of the extension name is capitalized as the prefix. For example, this configuration is available:

Main. package: net. sf. serfj. tests
Alias. serializers. package: serial
Suffix. serializers: This attribute is not defined. The default value is Serializer.

Search for the XML serialization class of the accounts resource. The qualified names of this class are as follows:

Net. sf. serfj. tests. account. serial. XmlAccountSerializer

5.3 model-oriented style

In this policy, after the Resource Name is singular and the attached main. package name is used, alias is not used. If you search for a controller class, its fully qualified class name is as follows:

Main. Package + "." + singularized (Resource Name) + "." + capitalized (singularized (Resource Name) + suffix. controllers.

If the following configuration attributes are defined:

Main. Package: net. SF. serfj. Tests
Suffix. controllers: This attribute is not defined. The default value is a null string.
Resource: banks

The framework will search for controller classes with the following qualified names:

Net. SF. serfj. Tests. Bank. Bank

If you search for the resource serializer, the class name uses the prefix. However, this prefix cannot be configured. It is fixed that the first letter of the extension name is capitalized as the prefix. For example, this configuration is available:

Main. Package: net. SF. serfj. Tests
Suffix. serializers: This attribute is not defined. The default value is serializer.

Search for the CSV serialization class of the accounts resource. The name of this class is as follows:

Net. SF. serfj. Tests. Account. csvaccountserializer

6. Non-Web Client

Serfj provides an interface class net. SF. serfj. Client. Client to initiate rest requests. It has four public methods (get, post, put, and delete) used to initiate a request.

The interface is very simple, so you only need to look at javadoc to use this class.


========================================================== ==========

PS:

1. Configure the servlet in the web. xml file for newly developed objects. For example:

<Servlet-mapping>
<Servlet-Name> restservlet </servlet-Name>
<URL-pattern>/phones/* </url-pattern>
</Servlet-mapping>

2. The resource name must be a plural number. Note that the system uses the Resource Name "S" or "es" as the object name. Nima is abnormal.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.