Simple implementation of Web request dispatch mechanism

Source: Internet
Author: User
Tags getmessage

  1. Web. XML definition

    <!--Spring Bean configuration--

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--start, scan annotations, cache defined URLs and corresponding processing class data--
    <listener>
    <listener-class>com.util.listener.ContextLoaderListener</listener-class>
    </listener>

    <!--filtering   character encoding filtering--
      <filter>
        <filter-name>characterencodingfilter </filter-name>
        <filter-class>com.util.filter.charcodefilter</filter-class
        <init-param>
          <param-name> Characterencoding</param-name>
          <param-value>utf-8</param-value
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>characterencodingfilter</filter-name>
        < Url-pattern>/*</url-pattern>
      </filter-mapping>

    <!--request to dispatch a servlet--
    <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>com.util.dispatcher.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet>

  2. 1 request dispatch, Web container startup scan URL annotations

public class Contextloaderlistener implements Servletcontextlistener {
Logger log =loggerfactory.getlogger (Contextloaderlistener.class);
@Override
public void contextdestroyed (Servletcontextevent arg0) {
TODO auto-generated Method Stub
Log.info ("context destroyed");
}
@Override
public void contextinitialized (Servletcontextevent arg0) {
try {
New Contextrootname (). Setcontextrootname (Arg0.getservletcontext (). Getcontextpath ());
Annotation Scan

New Annotationscanner (). sannclasses ();

The configuration to jump after the controller has been executed

New Analysisview (). Analysisactionviewproperties ();
} catch (ClassNotFoundException e) {
Log.error (E.getmessage ());
}
Log.info ("Context inited");
}

}

2.1.1 Annotation Scan


public class Annotationscanner {

private static list<string> packages = new arraylist<string> ();
static{
Packages.add ("Com.wqf.action.impl");
}
/** the path to be scanned */
private static list<string> paths = null;
TODO Scan to Required class method needs to be changed
public void Sannclasses () throws classnotfoundexception{
String Rootpath=getclass (). GetResource ("/"). GetFile (). toString ();
paths = Getpaths ();
for (String path:paths) {
File RootFile = new file (path);
File [] files = Rootfile.listfiles ();
String PackageName = Path.replace (RootPath, ""). Replace ('/', '. ') + ".";
for (File f:files) {
String className = F.getname (). substring (0, F.getname (). IndexOf (". Class"));
Class<?> clazz = Class.forName (packagename+classname);
Parseclass (Clazz);
}
}
}
public void Parseclass (class<?> clazz) {
String url1= "";
String url2= "";
annotation[] annotations = clazz.getannotations ();
for (Annotation annotation:annotations) {
if (Annotation.annotationtype (). Getsimplename (). Equals ("NameSpace")) {
NameSpace NameSpace = (NameSpace) annotation;
URL1 = Namespace.namespace ();
}
}
Method[] methods = Clazz.getdeclaredmethods ();
for (Method method:methods) {
annotation[] methodannotations = Method.getannotations ();
for (Annotation annotation:methodannotations) {
if (Annotation.annotationtype (). Getsimplename (). Equals ("requestmapping")) {
Requestmapping requestmapping = (requestmapping) annotation;
Url2 = Requestmapping.mapping ();
Mapclassmethodbean data = new Mapclassmethodbean ();
Data.setbean (Clazz);
Data.setm (method);
String url = modifyurl (url1 + url2);
Requestdata.setdata (URL, data);
}
}
}
}
private static string Modifyurl (string url) {
return URL;
}
TODO gets path to read from XML config file instead
Private List<string> getpaths () {
String Rootpath=getclass (). GetResource ("/"). GetFile (). toString ();
list<string> stringlist = new arraylist<string> ();
for (String scanpackage:packages) {
String Tmppath = Scanpackage.replace ('. ', '/');
Stringlist.add (RootPath + tmppath);
}
return stringlist;
}
}

2.1.2controller and jump to JSP page configuration

Firstaction/test.do = test.jsp


public class Analysisview {
Private String ViewPath = "/resource/viewnamesprop";

public void Analysisactionviewproperties () {
Properties prop = new properties ();
FileInputStream in;
try {
String Rootpath=getclass (). GetResource ("/"). GetFile (). toString ();
in = new FileInputStream (RootPath + viewPath);
Prop.load (in);
Iterator<string> it = Prop.stringpropertynames (). Iterator ();
while (It.hasnext ()) {
String Key=it.next ();
Viewnamedata.setdata (Key, Prop.getproperty (key));
}
In.close ();
} catch (FileNotFoundException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}

3. Core distribution Servlet


public class Dispatcherservlet extends HttpServlet {
/**
*
*/
Private static final long serialversionuid = 1L;
Logger log = Loggerfactory.getlogger (Dispatcherservlet.class);
Ibaseaction action = null;
Private String jsp = "JSP";
@Override
protected void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
Log.error ("No GET Request");
Return
DoPost (req, resp);
}

@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {

/**
* Determine the type of request to be distributed to different class
*/
String suffix = "";
if (Actionname.indexof (".")! =-1) {
suffix = actionname.substring (Actionname.indexof (".") + 1,actionname.indexof ("?") = =-1? Actionname.length (): Actionname.indexof ("?")-1);
//        }
if (jsp.equals (suffix)) {
Jspdispatcherservlet.getinstance (). DoPost (req, resp);
Return
//        }

try {//catch exception not thrown to foreground
String actionname = Req.getservletpath ();
ActionName = Actionname.indexof ("?") = =-1? ActionName:actionName.substring (0, Actionname.indexof ("?"));
/** the actual business class */
Class<?> clazz = null;
/** method of actual business */
method = null;
/** the variables passed in the foreground are uniformly encapsulated inside the context */
Context context = Contextfactory.createcontext (req, resp);
Proxyhandler handler = new Proxyhandler ();

String url = actionname.indexof (".") = =-1? actionName:actionName.substring (0, Actionname.indexof ("."));
Find the appropriate action on request
Mapclassmethodbean Classmethodbean = requestdata.getdata (URL);
if (Classmethodbean = = null) {
Log.info ("The URL is not configured");
Sendredirect (Viewnamedata.getnotfoundpage (), REQ,RESP);
Return
}
Clazz = Classmethodbean.getbean ();
method = Classmethodbean.getm ();
Cglibproxyhandler cglibproxy = new Cglibproxyhandler ();
Enhancer enhancer = new enhancer ();

Enhancer.setsuperclass (Clazz);
Enhancer.setcallback (Cglibproxy);

Object target = Clazz.cast (Ac.getbean (clazz));
Handler.settarget (target);
Object o =
Proxy.newproxyinstance (Target.getclass (). getClassLoader (),
Target.getclass (). Getinterfaces (),
handler);
Object o = enhancer.create ();
method[] Omethods = O.getclass (). Getdeclaredmethods ();
for (Method omethod:omethods) {
if (Omethod.getname (). Equals (Method.getname ())) {
try {
Omethod.invoke (o, context);
} catch (Illegalaccessexception e) {
Log.warn (E.getmessage ());
} catch (IllegalArgumentException e) {
Log.warn (E.getmessage ());
} catch (InvocationTargetException e) {
Log.warn (E.getmessage ());
}
}
}
If there is a corresponding view, the corresponding view of the jump

String viewName = Viewnamedata.getdata (ActionName);
if (viewName! = null) {
Sendredirect (VIEWNAME,REQ,RESP);
}
If there is no corresponding view
} catch (Exception E1) {
Log.error (E1.getmessage ());
Sendredirect (Viewnamedata.geterrorpage (), REQ,RESP);
}
}
private void Sendredirect (String fordardpage,httpservletrequest req, HttpServletResponse resp) throws ioexception{
String Rooturl = req.getscheme () + "://" + Req.getservername ()
+ ":" + req.getserverport ()
+ Req.getcontextpath ();
Resp.sendredirect (Rooturl + "/" + fordardpage);
}
}

Summary: When the Web container starts, listener scans the annotations of the Contrller package, forming the map<string URL, beanmethod<class controller, String method>> Data, when requested to go Dispatcherservlet, find the appropriate controller and method processing request according to the URL of the request.

If there is a corresponding JSP page configured after the request, jump to the corresponding JSP page.

A simple implementation, less than poor. You see addition when entertainment, engineering code follow-up, spit groove 51job Audit!!!

Simple implementation of Web request dispatch mechanism

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.