Write your own web framework----1

Source: Internet
Author: User

This article can be used as a << DIY struts– to build the MVC-based Web development Framework >> Book reading notes.
A schema diagram for a web framework that conforms to the Model 2 specification should look like this:

The servlet of the controller layer is a global butler who judges the individual requests to be handled by whom.
And each businesslogic decided to do exactly what.

From the diagram above, we can see that the core component is the servlet, which handles all requests.
So we'll first configure this servlet in Web. xml:

<?xml version= "1.0" encoding= "UTF-8"?><web-app version="2.4" 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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">    <display-name>Example of Web. xml</display-name>    <!--controller --    <servlet>        <servlet-name>Servlet</servlet-name>        <servlet-class>Com.gd.action.GdServlet</servlet-class>    </servlet>      <!--Intercept. Do requests--     <servlet-mapping>        <servlet-name>Servlet</servlet-name>         <url-pattern>*.do</url-pattern>     </servlet-mapping></Web-app>

The simple thing is to intercept all the. Do requests and give it to Com.gd.action.GdServlet to handle them.
And our "big housekeeper" at least satisfies the following format requirements.

 PackageCom.gd.action;ImportJava.io.IOException;ImportJava.util.Enumeration;ImportJava.util.HashMap;ImportJavax.servlet.RequestDispatcher;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public  class gdservlet extends httpservlet{    /**     *     */    Private Static Final LongSerialversionuid =-5277297442646870070L Public void Init()throwsServletexception {} Public void Doget(HttpServletRequest req, httpservletresponse Res)throwsServletexception, IOException {doPost (req, res); } Public void DoPost(HttpServletRequest req, httpservletresponse Res)throwsServletexception, IOException {dodispatcher (req, res); }Private void Do_dispatcher(HttpServletRequest req, httpservletresponse Res) {    } Public void Destroy() {            }}

Let's not consider the interior of Do_dispatcher for the time being. This is the biggest problem, let's put it to the end.
Solve the surrounding problem first:
1 if we have generated the corresponding model layer, then we have to pass the model layer data. The data comes from the request, and if we pass the request directly to a specific model layer, it does not conform to the Model 2 specification at all. So the best way is to strip the data from the request to form an object, and then pass the object to the concrete model layer.
What type of object is this? The data in the request is stored in the form of key-value, so use HashMap.

Private map<String,Object> Fromrequesttomap (httpservletrequest req) {Try{req.setcharacterencoding ("UTF-8"); }Catch(Unsupportedencodingexception E1) {//TODO auto-generated catch blockE1.printstacktrace (); } enumeration<String> E=req.getparameternames (); map<String,Object> infoin=Newhashmap<String,Object> (); while(E.hasmoreelements ()) {StringParaname = (String) e.nextelement ();//Why use getparametervalues instead of getparameter? Let's check the information ourselves.            Object[] Value=req.getparametervalues (Paraname);if(value==NULL) {Infoin.put (Paraname,""); }Else if(value.length==1) {Infoin.put (Paraname, value[0]); }Else{Infoin.put (paraname, value); }        }returnInfoin; }

2 All model layers should have a common interface, receive the above Infoin, process, and then return the data. If we look at the above, we can guess that the returned data should also be hashmap.
The interface should look like this:

publicinterface Action{    publicexecute(Map<String,Object> infoIn);}

3 We write one of the simplest logical model layers.

 PackageCom.gc.action;ImportJava.util.HashMap; Public  class helloworldactionimplements com. GD. action. Action {      /** This method is used to implement content to be processed without an incoming action * @param infoin * @return HashMap * *    PrivateHashmap<string, object>Doinit(hashmap<string, object> infoin)        {hashmap<string, object> infoout = Infoin; Infoout.put ("MSG","HelloWorld");returnInfoout; }@Override     PublicHashmap<string, object>doAction(hashmap<string, object> infoin) {//TODO auto-generated method stubString action = (Infoin.get ("Action") ==NULL) ?"": (String) Infoin.get ("Action"); hashmap<string, object> infoout =NewHashmap<string, object> ();if(Action.equals ("")) Infoout = This. Doinit (Infoin);Else if(Action.equals ("Show"))//....        returnInfoout; }}

Assume that the function of this action simply shows a helloword.
4 The specific model layer is already available, and the parameter types passed from the control layer to the model layer are also available. Down is the critical step, which is to specify the requested model in the control layer.
Suppose we ask the helloworldaction above and the last message is returned to index.jsp so we can send the following request address:
Http://localhost:8700/Struts2Demo/gc/dfd.do?logicName=HelloWorldAction&forwardJsp=index
That DFD is a random string.
Pass
String ss = Req.getservletpath ();
You can get the/gc/dif.do string.
And our helloworldaction are located
Package com.gc.action;
OK, Reflection.

Action action=NULL;StringServletpath=req.getservletpath ();StringSystempath=servletpath.split ("/")[1];//systempath is the GC .    StringLogicactionname=req.getparameter ("Logicname");//Logicactionname is helloworldaction    StringActionpath=getactionpath (Systempath, logicactionname);    action= (Action) class.forname (Actionpath). newinstance (); map<String,Object> infoout=action.doaction (infoin); PrivateStringGetactionpath (StringSystempath,StringActionName) {StringActionpath="";if(systempath!=NULL) actionpath="com."+systempath+". Action."+actionname;returnActionpath; }

In this way, we get the action to access and let it call its Doaction method.
The following tasks are returned to the view layer:

map<String,Object> infoout=action.doaction (infoin); Infoout.put ("Systempath", Systempath); Req.setattribute ("Infoout", infoout);    Forwards (req, res); PrivatevoidForwards (HttpServletRequest req, httpservletresponse Res) {//TODO auto-generated method stubmap<String,Object> infoout= (map<String,Object>) Req.getattribute ("Infoout");Try{Req.getrequestdispatcher ("/"+infoout.get ("Systempath")+"/jsp/"+ Infoout.get ("forwardjsp")+". JSP"). Forward (req, res); }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); }    }

Look at the view layer again:

<%@ page contenttype="text/html; CHARSET=GBK " language=" java " import=" java.sql.* " errorpage="" %><%@ page import="java.sql.*,java.util.*,javax.servlet.*, javax.servlet.http.*,java.text.*,java.math.*" %><% HashMap infoout = (request. getattribute ("Infoout") = = null)? New    HashMap (): (HASHMAP)request. getattribute ("Infoout"); String msg = infoout. Get ("MSG") = = null ? " " : (String) infoout. Get        ("MSG"); %><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" ><html><head><title>Implement HelloWorld output with new framework</title><style type="Text/css"><! -- Body    {  background-color: #FFFFFD;     font-family: Verdana, "song Body";     font-size: px;  font-style: normal; }--></style></head><body leftmargin="0" topmargin="0"><form name="Form1" action="/myapp/do" method= "POST"><H1><%=msg%><H1></form></body></html>

Let's look at the effect:

It seems pretty good.
In this section, we wrote a very sketchy web framework, which, of course, was ugly enough to show a HelloWorld. We are further perfecting him in the next section.

Write your own web framework----1

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.