Implementation of a simple MVC framework

Source: Internet
Author: User

1. Action interface

 PackageCom.togogo.webtoservice;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public InterfaceAction {/*** Default method of execution *@paramRequest object for incoming processing *@paramresponse Response object for incoming processing *@returnreturns a path to a jump*/     PublicString Execute (httpservletrequest request, httpservletresponse response);}

2, Baseaction's parent class

 PackageCom.togogo.webtoservice;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public Abstract classBaseactionImplementsAction {@Override Publicstring Execute (httpservletrequest request, HttpServletResponse response) {string result=NULL; String URI=Request.getrequesturi (); StringBuilder SB=NewStringBuilder (URI); String Path= Sb.substring (Uri.lastindexof ("!") + 1, Uri.lastindexof (".")); //It is known that the method is the same as the string of the uri parameter, then there is no method that can be called directly by method name (string) method? //implementation by method name, directly invoke the method, on the class dynamic technology        Try{Method Method= This. GetClass (). Getdeclaredmethod (Path, HttpServletRequest.class, HttpServletResponse.class); Result= (String) Method.invoke ( This, request, response); } Catch(nosuchmethodexception e) {E.printstacktrace (); } Catch(SecurityException e) {E.printstacktrace (); } Catch(illegalaccessexception e) {E.printstacktrace (); } Catch(IllegalArgumentException e) {E.printstacktrace (); } Catch(InvocationTargetException e) {E.printstacktrace (); }        returnresult; }}

3. Configuration class

 PackageCom.togogo.webtoservice;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.ResourceBundle;/*** Path and class name image * *@authorAdministrator **/ Public classConfig {//private static map<string, string> classnames = new hashmap<string,//string> ();    /*** via key * *@paramKey *@return     */     Public Staticstring GetClassName (string key, String config) {ResourceBundle bundle=NULL; if(config = =NULL||"". Equals (config)) {Bundle= Resourcebundle.getbundle ("Action"); } Else{Bundle=resourcebundle.getbundle (config); }        returnbundle.getstring (key); }    //Static {//classnames.put ("/user", "com.togogo.action.UserAction"); //classnames.put ("/admin", "com.togogo.action.AdminAction"); // }     Public Static voidMain (string[] args) {//used to read the Properties object in the form of a classResourceBundle bundle =resourcebundle. Getbundle ("Com.togogo.webtoservice.Action"); System.out.println (Bundle.getstring ("User")); }}

4, Dispacherservlet class

 PackageCom.togogo.webtoservice;Importjava.io.IOException;ImportJavax.servlet.ServletConfig;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classDispacherservletextendsHttpServlet {Private StaticString config=NULL; Private StaticString enconding= "UTF-8"; @Override Public voidInit (servletconfig config)throwsservletexception {String initconfig=config.getinitparameter ("config"); String initenconding=config.getinitparameter ("Enconding"); if(initconfig!=NULL) {Dispacherservlet.config=initconfig; }        //Web. XML configuration through the website descriptor file        if(initenconding!=NULL) {dispacherservlet.enconding=initenconding; }                Super. init (config); }    /*** Receive any request,*/@Overrideprotected voidService (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {Try{request.setcharacterencoding (enconding);            Response.setcharacterencoding (enconding); String URI=Request.getrequesturi (); StringBuilder SB=NewStringBuilder (URI); String Path= Sb.substring (Uri.lastindexof ("/") + 1, Uri.lastindexof ("!"));            SYSTEM.OUT.PRINTLN (path); String ClassName=Config.getclassname (path,config); Action Action=actionfactory.create (className); String result=Action.execute (request, response); if(Result.contains (":") {StringBuilder ResultStr=NewStringBuilder (Result); String Repath=resultstr.substring (Result.indexof (":") +1, Result.length ()); if(Result.contains ("redirect:") {response.sendredirect (Repath); }Else if(Result.contains ("Forward:") {request.getrequestdispatcher (Repath). Forward (request, response); }                            } Else{request.getrequestdispatcher (Result). Forward (request, response); }        } Catch(Exception e) {e.printstacktrace (); }    }}

5. Action Factory class

 PackageCom.togogo.webtoservice; Public classFactory { Public StaticAction Create (String ClassName) {Action action=NULL;Try{Action=(Action) class.forname (className). newinstance ();} Catch(ClassNotFoundException e) {e.printstacktrace ();}Catch(instantiationexception e) {e.printstacktrace ();}Catch(illegalaccessexception e) {e.printstacktrace ();}returnAction;}}

6, Test Testaction class

 Packagecom.togogo.action;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importcom.togogo.webtoservice.BaseAction; Public classUseractionextendsbaseaction {/*** User Login * *@paramRequest *@paramResponse *@return     */     PublicString Login (httpservletrequest request, httpservletresponse response) {System.out.println ("I'm logged in"); System.out.println ("I'm logged in------..."); return"Main.jsp"; }    /*** User Registration * *@paramRequest *@paramResponse *@return     */     PublicString Register (httpservletrequest request, httpservletresponse response) {System.out.println ("I'm registering."); return"Forward:main.jsp"; }        /*** User Registration * *@paramRequest *@paramResponse *@return     */     PublicString undo (HttpServletRequest request, httpservletresponse response) {System.out.println ("I'm undoing."); return"Redirect:main.jsp"; }}


Action.properties Mapping File

User=com.togogo.action.useraction

Web. XML configuration

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "><display-name>web_mvc_ Webtoservice</display-name> <!--This is a core controller--><servlet><servlet-name>dispacherservlet< /servlet-name><servlet-class>com.togogo.webtoservice.dispacherservlet</servlet-class>< Init-param> <param-name>config</param-name> <param-value>com.togogo.action.action</ Param-value></init-param></servlet><servlet-mapping><servlet-name>dispacherservlet </servlet-name><url-pattern>*.do</url-pattern></servlet-mapping><welcome-file-list ><welcome-file>default.jsp</welcome-file></welcome-file-list></web-app>

  

Test page

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

SOURCE Download:

Http://files.cnblogs.com/files/zhuyuejiu/web_mvc_webtoserive.zip

Implementation of a simple MVC framework

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.