first, the servlet base class, the Basecontroller class inherits HttpServlet, implements the Doget and Dopost methods, equivalent to Springmvc Dispacterservlet, We only need to register a basecontroller in Web. Xml. Basecontroller.ava PackageCom.easygo.controller;Importjava.io.IOException;Importjava.util.Properties;ImportJavax.servlet.ServletConfig;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classBasecontrollerextendsHttpServlet {/** * */ Private Static Final LongSerialversionuid = 1L; //invoke the Properties configuration file PrivateProperties properties=NewProperties (); //character encoding Collection PrivateString charset= "Utf-8"; @Override Public voidInit (servletconfig config)throwsservletexception {//gets the initialized parameter key valueString configname=config.getinitparameter ("ConfigName"); Try { //automatically load configuration filesProperties.load ( This. GetClass (). getClassLoader (). getResourceAsStream (ConfigName)); //obtaining a character encoding set from a configuration fileString tmp= properties.getproperty ("CharSet"); if(tmp!=NULL) {CharSet=tmp; } } Catch(IOException e) {e.printstacktrace (); System.out.println ("Read failed!" "); }} @Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {Try { //set the character encoding setreq.setcharacterencoding (CharSet); Resp.setcharacterencoding (CharSet); //get to URIString act=Req.getrequesturi (); //System.out.println (ACT); ///mvccontroller/user. do//User---Find com.uplooking.action.UserAction for config fileAct=act.substring (Act.lastindexof ("/") +1,act.lastindexof (". Do"))); //Gets the Classpath System.out.println (act);String classpath=properties.getproperty (ACT); //System.out.println (classPath); if(classpath==NULL|| Classpath.equals ("") {Resp.setcontenttype ("Text/html"); Resp.getwriter (). println ("There is no path you want to access!" "); return; } //make reflection callsClass Iactionclass =Class.forName (ClassPath); //Reverse InstanceIAction iaction=(iaction) iactionclass.newinstance (); //after handing over to the child method, just return String request response//Package return valueString result=Iaction.execute (req, resp); System.out.println ("Return value =" +result); //when there is a return value if(result!=NULL&&! "". Equals (Result)) { /*1 Default forwarding return "index.jsp"; 2 redirect Return "@red_index. JSP" 3json return "@json_ {XXXXXX}"*/ if(Result.contains ("@red_")){ // redirectResp.sendredirect (Result.split ("_") [1]); }Else if(Result.contains ("@json_") {Resp.setcontenttype ("Text/html"); Resp.getwriter (). println (Result.split ("_") [1]); Resp.getwriter (). Close (); }Else{req.getrequestdispatcher (Result). Forward (req, resp); } }Else{ //when there is no return valueResp.setcontenttype ("text/html"); Resp.getwriter (). println ("No return value!" "); return; } } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(instantiationexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }} @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doget (req, resp); } }------------------------------------------------------------------------------------------------------------- --------------------the Web. XML configuration:<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://xmlns.jcp.org/xml/ns/javaee" xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee/http Xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "id=" webapp_id "version=" 3.1 "> <display-name>mvccontroller </display-name> <servlet> <servlet-name>BaseController</servlet-name> <s ervlet-class>com.easygo.controller.basecontroller</servlet-class> <init-param> <param-name>configname</param-name> <param-value>a Ctionconfig.properties</param-value> </init-param> <load-on-startup>0</load-on-startu p> </servlet> <servlet-mapping> <servlet-name>BaseController</servlet-name> <url -pattern>*. Do</url-pattern> </servlet-mapping> <welcome-file-list> <WELCOME-FILE>INDEX.HTML</WELC Ome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file > <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list></web-app> ------------------------------------------------------------------------------------------------------- --------------------------IAction Interface, the action class implements the IAction interface Packagecom.easygo.action;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importcom.easygo.controller.IAction; Public classBookactionImplementsiaction{@Override PublicString Execute (httpservletrequest req, HttpServletResponse resp) {System.out.println ("Bookaction"); return"@red_index. JSP"; }} --------------------------------------------------------------------------------------------------------- ------------------------Actionconfig.properties,key represents the name of the URL request with a. Do suffix, and value is the full class name of the class used for reflection. CharSet=utf-8#user. DoUser=Com.easygo.action.useraction#book. Do Book=Com.easygo.action.BookActionjson=com.easygo.action.JsonAction --------------------------------------------------------------------------- ------------------------------------------------------Useraction.java class, the same principle as the method under Springmvc requestmapping annotation, for data return and page Jump. Packagecom.easygo.action;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importcom.easygo.controller.IAction; Public classUseractionImplementsiaction {@Override PublicString Execute (httpservletrequest req, HttpServletResponse resp) {System.out.println ("Useraction"); return"Index.jsp"; } /** Basecontroller.java httpservletrequest req, HttpServletResponse resp * Handle the method of the specified class by reflection * * | * | * * Processing Logic method * * Forwarding after processing * REDIRECT * JSON * * String x Point _ Pages/Data Accessed * | * | * | * This string--basecontroller * * @Override public String Execute (httpservletrequest req, Httpservletrespo NSE resp) {//TODO auto-generated method stub return null; } */} ------------------------------------------------------------------------------------------------------ ---------------------------Jsonaction.java is used for the return of JSON data. Packagecom.easygo.action;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importcom.easygo.controller.IAction; Public classJsonactionImplementsiaction{@Override PublicString Execute (httpservletrequest req, HttpServletResponse resp) {System.out.println ("Jsonaction"); return"@json_ {Asdsadsadsadsadad}"; }} --------------------------------------------------------------------------------------------------------- ------------------------index.jsp<%@ 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" >index.jsp</body> ------------------------------------------------------------------------------------------------------- --------------------------indexx.jsp<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "pageencoding= "Iso-8859-1"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > Do</a></body> ------------------------------------------------------------------------------------------------------- -------------------------- test: Run indexx.jsp (tomcat8.0) Click: user.do jump directly to Index.jspURL:http://localhost:8088/mvccontroller/user.doSpecific code: Link: https://pan.baidu.com/s/1spmcz0han_flazb1og5-pw Password: 77zi
Servlet+java reflection mechanism to implement MVC pattern