Write a Web server and framework with your bare hands in Java < chapter III: implementation and registration of service >

Source: Internet
Author: User

Use Java to write a Web server and frame with your bare hands < chapter I: NiO articles >

Write a Web server and framework with your bare hands in Java < chapter II: request and Response>

This chapter first the function of the web framework to say some, there is a prototype.

First make a service and bind to a regular address. Annotations and reflections are used.

Project address: telemarketer

Definition of Service

Telemarketer Service is a service that requests the address associated with it, and it serves you.

It requires only one method. And the requirement of this method is probably only input a request, can return a response so simple.

So that's it.

 Public Interface Service {    Response execute (Request request);}

The question is, how do you relate it to the URI? The first idea is to create a registry.

Binding of Service

This part of the code here, you can refer to the view

First, manual block.

Create a new class serviceregistry and put a static map in it:

private static map<string, service> services = new treemap<> ();

It also provides a way to:

Public static void Register (String pattern, service service) {Services.put (pattern, service);}

Then provide a way to find the service.

 Public Static Service Findservice (String pattern) {    for (map.entry<string, service> Entry: Services.entryset ()) {        if  (Pattern.matches (Entry.getkey ())) {            return  Entry.getvalue ();        }    }     return NULL ;}

Does this not determine the service object according to the request? Let the people have their own hands and clothing.

However, on second thought, so much trouble, but also let people find a special place register a lot? This is not convenient. Laziness is the first major productivity!

Then change the automatic block.

Come on, auto block.

A little think of spring those frames, with annotations to rely on injection that is flying, telemarketer can also! Come on, just do it!

Three key points to identify annotations first

      1. Determine target: Class
      2. Scoping: Run-time
      3. OK content: A string can put the address is good

 public @Interface  InService {     String urlpattern ();}

With this, write a service first mark. The address matches the root directory.

1 @InService (urlpattern = "^/$")2publicclassimplements  Service {3    @Override4public       Response Execute (Request Request) {5         returntonew fileresponse (status.success_200, Propertieshelper.gettemplatefile ("index.html")); 6     }7 }

propertieshelper.gettemplatefile ("index.html") returns an HTML file, temporarily without a tube. Fileresponse is the response that contains the contents of the file.

OK, now think about how to register with this note automatically?

Suppose we know that this class name is Edu.telemarketer.services.servicesimpls.IndexService. First reflect one:

class<?> aclass = Class.forName ("Edu.telemarketer.services.servicesimpls.IndexService");

Note that this Class.forName() differs from the ClassLoader load () method: Class.forName () initializes the static domain in the class, and any static will be ready, and ClassLoader's load will not have this effect.

Once you have this class object, get the Inservice callout

InService annotation = aclass.getannotation (InService. Class);

Judge if it is null and determine if Service.class is the interface for this class. If all is satisfied that is the class we are looking for. Instantiate it! Register it!

if null && Service. class . IsAssignableFrom (AClass)) {    Controller.register (Annotation.urlpattern (), Aclass.assubclass (Service. class ). newinstance ());}

Note the difference between the IsAssignableFrom and instanceof here, IsAssignableFrom to the left is the parent class or interface on the right.

The whole process is to get the root directory and then recursively scan all the. Class for the above judgment. And the reflection of the time to use the full name, and then record the packet path. Specific can view the source code.

This process also encountered a problem: in the beginning I acquired the Edu.telemarketer package name to convert to a path with the Name.replaceall ("\.", File.separator). An exception was tested in the Windows environment. After the verification found that ReplaceAll is not allowed to appear "\", will cause confusion. Specific point here Stackoverflow--replaceall "/" with File.separator

This is the end of the automatic block.

Use in Controller

A controller is a class that implements the runnable. It's run is probably a process like this.

1 Request request = Request.parsefrombuffer (buffer); 2 Service service =Serviceregistry.findservice (Request.getfilepath ()); 3 Response Response = service.execute (request); 4 Selectionkey key = Channel.register (selector, selectionkey.op_write); 5 Key.attach (response);

Start up and see if the page is out.

Some information in the server's first domain, such as maintaining links or adding cookies, should be processed before and after the service is submitted for processing. These aspects will be further improved.

Write a Web server and framework with your bare hands in Java < chapter III: implementation and registration of service >

Related Article

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.