SPRINGMVC Framework Implementation

Source: Internet
Author: User

The SPRINGMVC framework is a spring implementation based on the MVC design pattern, which focuses on three core functions 1 Jump 2 IOC 3 AOP (temporarily not implemented)

Manual writing Springmvc Framework, through annotations to achieve the jump and IOC two core functions, the project structure is as follows:

Create annotations separately @controller

Package com.hongsen.annotation; @Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documentedpublic @ Interface Controller {    String value ();}

Creating @requestmapping Annotations

Package com.hongsen.annotation; @Target ({elementtype.method,elementtype.type}) @Retention (retentionpolicy.runtime ) @Documentedpublic @interface requestmapping {    String value ();}

Creating @resource Annotations

Package Com.hongsen.annotation, @Target (Elementtype.field) @Retention (retentionpolicy.runtime) public @interface Resource {    String value ();}

Creating @service Annotations

Package com.hongsen.annotation; @Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documentedpublic @ Interface Service {    String value ();}

Create a servlet with the following code:

Package com.hongsen.servlet;/** * SPRINGMVC function * <p> * 1 Jump * 2 IOC * 3 AOP * * @author Wanghongsen 2018.07.27 */pub    Lic class Dispatcherservlet extends HttpServlet {private static final long serialversionuid = 1L;    Private list<string> classlist = new arraylist<> ();    Private map<string, object> beaninstancemap = new hashmap<> ();    Private map<string, method> urlhandlermap = new hashmap<> ();     /** * Servlet Initialization method * 1 Scan Scan Package path * 2 constructs all class collections (list<string>) * 3 constructs all Bean instance collections (beanname-> beans) * 4 constructs all requests handler jump (URI-and method) */public void init () throws Servletexception {System.out.println ("        Init () Start ");        String Scanbasepath = "Com.hongsen";        Scan (Scanbasepath);        Initbeaninstance ();        IOC ();    Initurlhandlermap (); private void Scan (String scanbasepath) {URL url = this.getclass (). GetResource ("/" + Scanbasepath.replace (".")        , "/")); String BasefIlepath = Url.getfile ();        File Basefile = new file (Basefilepath);        string[] subfilepaths = Basefile.list (); for (String subfilepath:subfilepaths! = null? subfilepaths:new string[0]) {File Subfile = new File (basefi            Lepath + Subfilepath);            if (Subfile.isdirectory ()) {Scan (Scanbasepath + "." + Subfilepath);            } else {Classlist.add (Scanbasepath + "." + Subfilepath); }        }    }
private void Initbeaninstance () {for (String beanname:classlist) {try {Beanname = Beanname.replace (". Class", ""); Class Beanclass = Class.forName (beanname); try {if (beanclass.isannotationpresent (Controller.class)) {Controller controll ER = (Controller) beanclass.getannotation (Controller.class); Beaninstancemap.put (Controller.value (), beanclass.newinstance ()); } else if (Beanclass.isannotationpresent (Service.class)) {Service service = (service) beanclass.ge Tannotation (Service.class); Beaninstancemap.put (Service.value (), beanclass.newinstance ()); }} catch (Instantiationexception | Illegalaccessexception e) {e.printstacktrace (); }} catch (ClassNotFoundException e) {e.printstacktrace (); }}} private void IOC () {for (String beanname:classlist) {try {b Eanname = Beanname.replace (". Class", ""); Class Beanclass = Class.forName (beanname); field[] fields = Beanclass.getdeclaredfields (); for (Field field:fields) {if (Field.isannotationpresent (Resource.class)) {Re SOURCE resource = Field.getannotation (Resource.class); String val = Resource.value (); try {field.setaccessible (true); Service service = (service) beanclass.getannotation (Service.class); if (service! = null) {Field.set (Beaninstancemap.get (Service.value ()), Beaninstancemap.get ( val)); } else {Controller Controller = (Controller) beanclass.getannotation (ControlLer.class); if (Controller = null) {Field.set (Beaninstancemap.get (Controller.value ()), Beaninstan Cemap.get (Val)); }}} catch (Illegalaccessexception e) {E.PR Intstacktrace (); }}}} catch (ClassNotFoundException e) {e.printstacktrace () ; }}} private void Initurlhandlermap () {for (String beanname:classlist) {try { Beanname = Beanname.replace (". Class", ""); Class Beanclass = Class.forName (beanname); if (Beanclass.isannotationpresent (Requestmapping.class)) {requestmapping Basereqmap = (requestmapping) Beanclass.getannotation (Requestmapping.class); if (basereqmap! = null) {StringRequestbaseurl = Basereqmap.value (); Method[] methods = Beanclass.getmethods (); for (Method method:methods) {requestmapping Reqmap = method.getannotation (requestmapping.cla SS); if (reqmap! = null) {urlhandlermap.put (Requestbaseurl + reqmap.value (), method); }}}}} catch (Classnotfoundexcep tion e) {e.printstacktrace (); }}} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Javax.servlet.Se Rvletexception, IOException {doget (request, response); } protected void Doget (HttpServletRequest request, httpservletresponse response) throws Javax.servlet.ServletException , IOException {String uri = Request.getrequesturi (); String ContextPath = Request.getcontextpath(); String Requesturl = Uri.replace (ContextPath, ""); method = Urlhandlermap.get (Requesturl); if (method = = null) {return; } Class Beanclass = Method.getdeclaringclass (); Controller Controller = (Controller) beanclass.getannotation (Controller.class); Object bean = Beaninstancemap.get (Controller.value ()); try {map<string, string[]> requestparametermap = Request.getparametermap (); object[] args = new Object[requestparametermap.entryset (). Size ()]; int index = 0; For (Map.entry Entry:requestParameterMap.entrySet ()) {Args[index] = Entry.getvalue (); index++; } method.invoke (bean, args); } catch (Illegalaccessexception | InvocationTargetException e) {e.printstacktrace (); } }}

Web. XML automatically generates corresponding code after the servlet is created

<load-on-startup> Add this tag, when Tomcat starts automatically loads the specified servlet greater than or equal to 0 o'clock start tomcat loads the servlet's init () method The smaller the number, the higher the priority of the load

<url-pattern>/This tag is the Tomcat request scan path, which will call the servlet corresponding Doget or Dopost method

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns= "Http://xmlns.jcp.org/xml/ns/javaee"         xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"         xsi:schemalocation= "HTTP://XMLNS.JCP.ORG/XML/NS/JAVAEE/HTTP// Xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "         version=" 3.1 ">    <servlet>        <servlet-name >DispatcherServlet</servlet-name>        <servlet-class>com.hongsen.servlet.dispatcherservlet</ Servlet-class>        <load-on-startup>1</load-on-startup>
    </servlet>    <servlet-mapping>        <servlet-name>DispatcherServlet</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping></web-app>

Creating a Controller class

Package Com.hongsen.controller, @Controller ("TestController") @RequestMapping ("/test") public class TestController {    @Resource ("Testaddservice")    private Testaddserviceimpl testaddservice;    @Resource ("Testdelservice")    private Testdelserviceimpl testdelservice;    @RequestMapping ("/add.json") public    void Testadd () {        testaddservice.add ();    }    @RequestMapping ("/del.json") public    void Testdel (Object Num1, Object num2) {        Testdelservice.del ( Num1.tostring (), num2.tostring ());}    }

Creating service Interfaces and implementing classes

Package Com.hongsen.service;public interface Testaddservice {    void Add (String num);}

Package Com.hongsen.service, @Service ("Testaddservice") public class Testaddserviceimpl implements testaddservice{    @Override public    void Add (String num) {        System.out.println ("The Add method executes! ");    }}

After the deployment of Tomcat starts successfully:

Visit: Http://localhost:8080/test/add.json

SPRINGMVC Framework Implementation

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.