Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
在 Spring 框架中,Bean 的實(shí)例化流程通常包括以下步驟:
這是 Spring Bean 的一般實(shí)例化流程,具體的實(shí)現(xiàn)細(xì)節(jié)可能會(huì)根據(jù)不同的配置方式和 Bean 類(lèi)型而有所不同。希望這個(gè)回答能夠幫助你理解 Spring Bean 的實(shí)例化過(guò)程。
在 Spring 框架中,Bean 的生命周期可以分為以下階段:
在整個(gè)生命周期中,Spring 容器負(fù)責(zé)管理 Bean 的創(chuàng)建、初始化和銷(xiāo)毀等過(guò)程,開(kāi)發(fā)人員可以通過(guò)配置文件或注解來(lái)定義 Bean 的生命周期行為,以滿(mǎn)足不同的需求。
總的來(lái)說(shuō),Spring Bean 的生命周期可以概括為實(shí)例化、屬性設(shè)置、初始化、可用和銷(xiāo)毀等階段。希望這個(gè)回答對(duì)你有幫助。
Bean的完整生命周期經(jīng)歷了各種方法調(diào)用,這些方法可以劃分為以下幾類(lèi):
具體而言,流程如下
https://blog.csdn.net/dreambyday/article/details/125473596
Spring 框架在啟動(dòng)過(guò)程中會(huì)執(zhí)行一系列步驟來(lái)初始化應(yīng)用程序上下文并準(zhǔn)備好處理請(qǐng)求。以下是 Spring 啟動(dòng)的主要流程:
總的來(lái)說(shuō),Spring 啟動(dòng)流程包括加載配置文件、創(chuàng)建應(yīng)用程序上下文、注冊(cè) Bean、依賴(lài)注入、執(zhí)行生命周期回調(diào)等步驟,最終使應(yīng)用程序準(zhǔn)備好接收和處理請(qǐng)求。
總結(jié)為一句話(huà)就是:在目標(biāo)對(duì)象(target object)的某些方法(jointpoint)添加不同種類(lèi)的操作(通知、增強(qiáng)操處理),最后通過(guò)某些方法(weaving、織入操作)實(shí)現(xiàn)一個(gè)新的代理目標(biāo)對(duì)象。
Spring AOP是基于動(dòng)態(tài)代理的,如果要代理的對(duì)象實(shí)現(xiàn)了某個(gè)接口,那么Spring AOP就會(huì)使用JDK動(dòng)態(tài)代理去創(chuàng)建代理對(duì)象;而對(duì)于沒(méi)有實(shí)現(xiàn)接口的對(duì)象,就無(wú)法使用JDK動(dòng)態(tài)代理,轉(zhuǎn)而使用CGlib動(dòng)態(tài)代理生成一個(gè)被代理對(duì)象的子類(lèi)來(lái)作為代理。
當(dāng)然也可以使用AspectJ,Spring AOP中已經(jīng)集成了AspectJ,AspectJ應(yīng)該算得上是Java生態(tài)系統(tǒng)中最完整的AOP框架了。使用AOP之后我們可以把一些通用功能抽象出來(lái),在需要用到的地方直接使用即可,這樣可以大大簡(jiǎn)化代碼量。我們需要增加新功能也方便,提高了系統(tǒng)的擴(kuò)展性。日志功能、事務(wù)管理和權(quán)限管理等場(chǎng)景都用到了AOP。
實(shí)現(xiàn) AOP 的技術(shù),主要分為兩大類(lèi):
流程說(shuō)明:
1.客戶(hù)端(瀏覽器)發(fā)送請(qǐng)求,直接請(qǐng)求到DispatcherServlet。
2.DispatcherServlet根據(jù)請(qǐng)求信息調(diào)用HandlerMapping,解析請(qǐng)求對(duì)應(yīng)的Handler。
3.解析到對(duì)應(yīng)的Handler(也就是我們平常說(shuō)的Controller控制器)。
4.HandlerAdapter會(huì)根據(jù)Handler來(lái)調(diào)用真正的處理器來(lái)處理請(qǐng)求和執(zhí)行相對(duì)應(yīng)的業(yè)務(wù)邏輯。
5.處理器處理完業(yè)務(wù)后,會(huì)返回一個(gè)ModelAndView對(duì)象,Model是返回的數(shù)據(jù)對(duì)象,View是邏輯上的View。
6.ViewResolver會(huì)根據(jù)邏輯View去查找實(shí)際的View。
7.DispatcherServlet把返回的Model傳給View(視圖渲染)。
8.把View返回給請(qǐng)求者(瀏覽器)。
@Data@ConfigurationProperties(prefix="com.pdai")
public class DemoProperties {
private String version;
private String name;
}
@Configuration@EnableConfigurationProperties(DemoProperties.class)
public class DemoAutoConfiguration {
@Bean
public com.pdai.demo.module.DemoModule demoModule(DemoProperties properties){
com.pdai.demo.module.DemoModule demoModule=new com.pdai.demo.module.DemoModule();
demoModule.setName(properties.getName());
demoModule.setVersion(properties.getVersion());return demoModule;
}
}
在META-INF下創(chuàng)建spring.factory文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.pdai.demospringbootstarter.DemoAutoConfiguration
了應(yīng)對(duì)在SpringBoot中的高并發(fā)及優(yōu)化訪問(wèn)速度,我們一般會(huì)把頁(yè)面上的數(shù)據(jù)查詢(xún)出來(lái),然后放到redis中進(jìn)行緩存。減少數(shù)據(jù)庫(kù)的壓力。
在SpringBoot中一般使用
thymeleafViewResolver.getTemplateEngine().process("goodlist", ctx);
進(jìn)行頁(yè)面的渲染,而這個(gè)ctx就是SpringWebContext對(duì)象,我們一般進(jìn)行如下獲取:
SpringWebContext swc=new SpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);
在SpringBoot 1.X的版本中以上代碼可以使用。但在SpringBoot 2.0中,就無(wú)法找到SpringWebContext了。那應(yīng)該如何去解決這個(gè)問(wèn)題呢?
說(shuō)一下我的思路,.process方法中ctx所在參數(shù)所需要的類(lèi)型為接口IContext
image
也就是需要有實(shí)現(xiàn)了IContext的類(lèi)就可以了,然后進(jìn)入IContext接口找所有的實(shí)現(xiàn)類(lèi)
image
然后看到WebContext似乎有些像上面所用的SpringWebContext。即做出如下改變,完美實(shí)現(xiàn)了thymeleaf的頁(yè)面渲染。
WebContext ctx=new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
html=thymeleafViewResolver.getTemplateEngine().process("goodlist", ctx);
在SpringBoot 2.0中使用上述代碼,可以完全替代。
(當(dāng)然在下不才,暫時(shí)只找到了這種辦法,在網(wǎng)絡(luò)上也沒(méi)找到對(duì)應(yīng)的比較不錯(cuò)的策略。所以分享出來(lái),以備分享出來(lái),幫助遇到此問(wèn)題的程序員們。如果大家有什么更好的處理辦法可以一起互相交流哦)
目前我正在搞基于SpringBoot、Redis、消息隊(duì)列的秒殺小項(xiàng)目,主要還是為了梳理如何解決高并發(fā)的問(wèn)題過(guò)程。
GitHub:https://github.com/iquanzhan/SecKillShop
歡迎點(diǎn)擊Start哦
所用技術(shù)
1.后端:SpringBoot、JSR303、MyBatis
2.前端:Thymeleaf、BootStrap、Jquery
3.中間件:RabbitMQ、Redis、Druid
Spring框架對(duì)于Java后端程序員來(lái)說(shuō)再熟悉不過(guò)了,以前只知道它用的反射實(shí)現(xiàn)的,但了解之后才知道有很多巧妙的設(shè)計(jì)在里面。如果不看Spring的源碼,你將會(huì)失去一次和大師學(xué)習(xí)的機(jī)會(huì):它的代碼規(guī)范,設(shè)計(jì)思想很值得學(xué)習(xí)。我們程序員大部分人都是野路子,不懂什么叫代碼規(guī)范。寫(xiě)了一個(gè)月的代碼,最后還得其他老司機(jī)花3天時(shí)間重構(gòu),相信大部分老司機(jī)都很頭疼看新手的代碼。
廢話(huà)不多說(shuō),我們進(jìn)入今天的正題,在Web應(yīng)用程序設(shè)計(jì)中,MVC模式已經(jīng)被廣泛使用。SpringMVC以DispatcherServlet為核心,負(fù)責(zé)協(xié)調(diào)和組織不同組件以完成請(qǐng)求處理并返回響應(yīng)的工作,實(shí)現(xiàn)了MVC模式。想要實(shí)現(xiàn)自己的SpringMVC框架,需要從以下幾點(diǎn)入手:
一、了解SpringMVC運(yùn)行流程及九大組件
二、梳理自己的SpringMVC的設(shè)計(jì)思路
三、實(shí)現(xiàn)自己的SpringMVC框架
一、了解SpringMVC運(yùn)行流程及九大組件
1、SpringMVC的運(yùn)行流程
⑴ 用戶(hù)發(fā)送請(qǐng)求至前端控制器DispatcherServlet
⑵ DispatcherServlet收到請(qǐng)求調(diào)用HandlerMapping處理器映射器。
⑶ 處理器映射器根據(jù)請(qǐng)求url找到具體的處理器,生成處理器對(duì)象及處理器攔截器(如果有則生成)一并返回給DispatcherServlet。
⑷ DispatcherServlet通過(guò)HandlerAdapter處理器適配器調(diào)用處理器
⑸ 執(zhí)行處理器(Controller,也叫后端控制器)。
⑹ Controller執(zhí)行完成返回ModelAndView
⑺ HandlerAdapter將controller執(zhí)行結(jié)果ModelAndView返回給DispatcherServlet
⑻ DispatcherServlet將ModelAndView傳給ViewReslover視圖解析器
⑼ ViewReslover解析后返回具體View
⑽ DispatcherServlet對(duì)View進(jìn)行渲染視圖(即將模型數(shù)據(jù)填充至視圖中)。
⑾ DispatcherServlet響應(yīng)用戶(hù)。
從上面可以看出,DispatcherServlet有接收請(qǐng)求,響應(yīng)結(jié)果,轉(zhuǎn)發(fā)等作用。有了DispatcherServlet之后,可以減少組件之間的耦合度。
2、SpringMVC的九大組件(ref:【SpringMVC】9大組件概覽)
protected void initStrategies(ApplicationContext context) { //用于處理上傳請(qǐng)求。處理方法是將普通的request包裝成MultipartHttpServletRequest,后者可以直接調(diào)用getFile方法獲取File. initMultipartResolver(context); //SpringMVC主要有兩個(gè)地方用到了Locale:一是ViewResolver視圖解析的時(shí)候;二是用到國(guó)際化資源或者主題的時(shí)候。 initLocaleResolver(context); //用于解析主題。SpringMVC中一個(gè)主題對(duì)應(yīng)一個(gè)properties文件,里面存放著跟當(dāng)前主題相關(guān)的所有資源、 //如圖片、css樣式等。SpringMVC的主題也支持國(guó)際化, initThemeResolver(context); //用來(lái)查找Handler的。 initHandlerMappings(context); //從名字上看,它就是一個(gè)適配器。Servlet需要的處理方法的結(jié)構(gòu)卻是固定的,都是以request和response為參數(shù)的方法。 //如何讓固定的Servlet處理方法調(diào)用靈活的Handler來(lái)進(jìn)行處理呢?這就是HandlerAdapter要做的事情 initHandlerAdapters(context); //其它組件都是用來(lái)干活的。在干活的過(guò)程中難免會(huì)出現(xiàn)問(wèn)題,出問(wèn)題后怎么辦呢? //這就需要有一個(gè)專(zhuān)門(mén)的角色對(duì)異常情況進(jìn)行處理,在SpringMVC中就是HandlerExceptionResolver。 initHandlerExceptionResolvers(context); //有的Handler處理完后并沒(méi)有設(shè)置View也沒(méi)有設(shè)置ViewName,這時(shí)就需要從request獲取ViewName了, //如何從request中獲取ViewName就是RequestToViewNameTranslator要做的事情了。 initRequestToViewNameTranslator(context); //ViewResolver用來(lái)將String類(lèi)型的視圖名和Locale解析為View類(lèi)型的視圖。 //View是用來(lái)渲染頁(yè)面的,也就是將程序返回的參數(shù)填入模板里,生成html(也可能是其它類(lèi)型)文件。 initViewResolvers(context); //用來(lái)管理FlashMap的,F(xiàn)lashMap主要用在redirect重定向中傳遞參數(shù)。 initFlashMapManager(context); }
二、梳理SpringMVC的設(shè)計(jì)思路
本文只實(shí)現(xiàn)自己的@Controller、@RequestMapping、@RequestParam注解起作用,其余SpringMVC功能讀者可以嘗試自己實(shí)現(xiàn)。
1、讀取配置
從圖中可以看出,SpringMVC本質(zhì)上是一個(gè)Servlet,這個(gè) Servlet 繼承自 HttpServlet。FrameworkServlet負(fù)責(zé)初始化SpringMVC的容器,并將Spring容器設(shè)置為父容器。因?yàn)楸疚闹皇菍?shí)現(xiàn)SpringMVC,對(duì)于Spring容器不做過(guò)多講解(有興趣同學(xué)可以看看我另一篇文章:向spring大佬低頭--大量源碼流出解析)。
為了讀取web.xml中的配置,我們用到ServletConfig這個(gè)類(lèi),它代表當(dāng)前Servlet在web.xml中的配置信息。通過(guò)web.xml中加載我們自己寫(xiě)的MyDispatcherServlet和讀取配置文件。
2、初始化階段
在前面我們提到DispatcherServlet的initStrategies方法會(huì)初始化9大組件,但是這里將實(shí)現(xiàn)一些SpringMVC的最基本的組件而不是全部,按順序包括:
3、運(yùn)行階段
每一次請(qǐng)求將會(huì)調(diào)用doGet或doPost方法,所以統(tǒng)一運(yùn)行階段都放在doDispatch方法里處理,它會(huì)根據(jù)url請(qǐng)求去HandlerMapping中匹配到對(duì)應(yīng)的Method,然后利用反射機(jī)制調(diào)用Controller中的url對(duì)應(yīng)的方法,并得到結(jié)果返回。按順序包括以下功能:
三、實(shí)現(xiàn)自己的SpringMVC框架
工程文件及目錄:
首先,新建一個(gè)maven項(xiàng)目,在pom.xml中導(dǎo)入以下依賴(lài):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.liugh</groupId> <artifactId>liughMVC</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> </dependencies></project>
接著,我們?cè)赪EB-INF下創(chuàng)建一個(gè)web.xml,如下配置:
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <servlet> <servlet-name>MySpringMVC</servlet-name> <servlet-class>com.liugh.servlet.MyDispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>application.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MySpringMVC</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping></web-app>
application.properties文件中只是配置要掃描的包到SpringMVC容器中。
scanPackage=com.liugh.core
創(chuàng)建自己的Controller注解,它只能標(biāo)注在類(lèi)上面:
package com.liugh.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface MyController { /** * 表示給controller注冊(cè)別名 * @return */ String value() default ""; }
RequestMapping注解,可以在類(lèi)和方法上:
package com.liugh.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.TYPE,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface MyRequestMapping { /** * 表示訪問(wèn)該方法的url * @return */ String value() default ""; }
RequestParam注解,只能注解在參數(shù)上
package com.liugh.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface MyRequestParam { /** * 表示參數(shù)的別名,必填 * @return */ String value(); }
然后創(chuàng)建MyDispatcherServlet這個(gè)類(lèi),去繼承HttpServlet,重寫(xiě)init方法、doGet、doPost方法,以及加上我們第二步分析時(shí)要實(shí)現(xiàn)的功能:
package com.liugh.servlet;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.lang.reflect.Method;import java.net.URL;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Properties;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.liugh.annotation.MyController;import com.liugh.annotation.MyRequestMapping;public class MyDispatcherServlet extends HttpServlet{ private Properties properties=new Properties(); private List<String> classNames=new ArrayList<>(); private Map<String, Object> ioc=new HashMap<>(); private Map<String, Method> handlerMapping=new HashMap<>(); private Map<String, Object> controllerMap=new HashMap<>(); @Override public void init(ServletConfig config) throws ServletException { //1.加載配置文件 doLoadConfig(config.getInitParameter("contextConfigLocation")); //2.初始化所有相關(guān)聯(lián)的類(lèi),掃描用戶(hù)設(shè)定的包下面所有的類(lèi) doScanner(properties.getProperty("scanPackage")); //3.拿到掃描到的類(lèi),通過(guò)反射機(jī)制,實(shí)例化,并且放到ioc容器中(k-v beanName-bean) beanName默認(rèn)是首字母小寫(xiě) doInstance(); //4.初始化HandlerMapping(將url和method對(duì)應(yīng)上) initHandlerMapping(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { //處理請(qǐng)求 doDispatch(req,resp); } catch (Exception e) { resp.getWriter().write("500!! Server Exception"); } } private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception { if(handlerMapping.isEmpty()){ return; } String url=req.getRequestURI(); String contextPath=req.getContextPath(); url=url.replace(contextPath, "").replaceAll("/+", "/"); if(!this.handlerMapping.containsKey(url)){ resp.getWriter().write("404 NOT FOUND!"); return; } Method method=this.handlerMapping.get(url); //獲取方法的參數(shù)列表 Class<?>[] parameterTypes=method.getParameterTypes(); //獲取請(qǐng)求的參數(shù) Map<String, String[]> parameterMap=req.getParameterMap(); //保存參數(shù)值 Object [] paramValues=new Object[parameterTypes.length]; //方法的參數(shù)列表 for (int i=0; i<parameterTypes.length; i++){ //根據(jù)參數(shù)名稱(chēng),做某些處理 String requestParam=parameterTypes[i].getSimpleName(); if (requestParam.equals("HttpServletRequest")){ //參數(shù)類(lèi)型已明確,這邊強(qiáng)轉(zhuǎn)類(lèi)型 paramValues[i]=req; continue; } if (requestParam.equals("HttpServletResponse")){ paramValues[i]=resp; continue; } if(requestParam.equals("String")){ for (Entry<String, String[]> param : parameterMap.entrySet()) { String value=Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ","); paramValues[i]=value; } } } //利用反射機(jī)制來(lái)調(diào)用 try { method.invoke(this.controllerMap.get(url), paramValues);//第一個(gè)參數(shù)是method所對(duì)應(yīng)的實(shí)例 在ioc容器中 } catch (Exception e) { e.printStackTrace(); } } private void doLoadConfig(String location){ //把web.xml中的contextConfigLocation對(duì)應(yīng)value值的文件加載到流里面 InputStream resourceAsStream=this.getClass().getClassLoader().getResourceAsStream(location); try { //用Properties文件加載文件里的內(nèi)容 properties.load(resourceAsStream); } catch (IOException e) { e.printStackTrace(); }finally { //關(guān)流 if(null!=resourceAsStream){ try { resourceAsStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void doScanner(String packageName) { //把所有的.替換成/ URL url=this.getClass().getClassLoader().getResource("/"+packageName.replaceAll("\\.", "/")); File dir=new File(url.getFile()); for (File file : dir.listFiles()) { if(file.isDirectory()){ //遞歸讀取包 doScanner(packageName+"."+file.getName()); }else{ String className=packageName +"." +file.getName().replace(".class", ""); classNames.add(className); } } } private void doInstance() { if (classNames.isEmpty()) { return; } for (String className : classNames) { try { //把類(lèi)搞出來(lái),反射來(lái)實(shí)例化(只有加@MyController需要實(shí)例化) Class<?> clazz=Class.forName(className); if(clazz.isAnnotationPresent(MyController.class)){ ioc.put(toLowerFirstWord(clazz.getSimpleName()),clazz.newInstance()); }else{ continue; } } catch (Exception e) { e.printStackTrace(); continue; } } } private void initHandlerMapping(){ if(ioc.isEmpty()){ return; } try { for (Entry<String, Object> entry: ioc.entrySet()) { Class<? extends Object> clazz=entry.getValue().getClass(); if(!clazz.isAnnotationPresent(MyController.class)){ continue; } //拼url時(shí),是controller頭的url拼上方法上的url String baseUrl=""; if(clazz.isAnnotationPresent(MyRequestMapping.class)){ MyRequestMapping annotation=clazz.getAnnotation(MyRequestMapping.class); baseUrl=annotation.value(); } Method[] methods=clazz.getMethods(); for (Method method : methods) { if(!method.isAnnotationPresent(MyRequestMapping.class)){ continue; } MyRequestMapping annotation=method.getAnnotation(MyRequestMapping.class); String url=annotation.value(); url=(baseUrl+"/"+url).replaceAll("/+", "/"); handlerMapping.put(url,method); controllerMap.put(url,clazz.newInstance()); System.out.println(url+","+method); } } } catch (Exception e) { e.printStackTrace(); } } /** * 把字符串的首字母小寫(xiě) * @param name * @return */ private String toLowerFirstWord(String name){ char[] charArray=name.toCharArray(); charArray[0] +=32; return String.valueOf(charArray); } }
這里我們就開(kāi)發(fā)完了自己的SpringMVC,現(xiàn)在我們測(cè)試一下:
package com.liugh.core.controller;import java.io.IOException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.liugh.annotation.MyController;import com.liugh.annotation.MyRequestMapping;import com.liugh.annotation.MyRequestParam;@MyController@MyRequestMapping("/test")public class TestController { @MyRequestMapping("/doTest") public void test1(HttpServletRequest request, HttpServletResponse response, @MyRequestParam("param") String param){ System.out.println(param); try { response.getWriter().write( "doTest method success! param:"+param); } catch (IOException e) { e.printStackTrace(); } } @MyRequestMapping("/doTest2") public void test2(HttpServletRequest request, HttpServletResponse response){ try { response.getWriter().println("doTest2 method success!"); } catch (IOException e) { e.printStackTrace(); } } }
訪問(wèn)http://localhost:8080/liughMVC/test/doTest?param=liugh如下:
訪問(wèn)一個(gè)不存在的試試:
到這里我們就大功告成了!
我自己在騰訊課堂上也有講過(guò)一堂手寫(xiě)springMVC的直播分享,有感興趣的可以來(lái)看看
https://pan.baidu.com/s/17v3syshIGQWjCHL0yi73Cg
1,3分鐘讀懂Spring核心源碼;
2,SpringMVC與Spring框架關(guān)系;
3,SpringMVC的所有注解定義實(shí)戰(zhàn);
4,手寫(xiě)SpringMVC框架實(shí)戰(zhàn);
5,Tomcat加載進(jìn)行測(cè)試實(shí)戰(zhàn);
6,互動(dòng)答疑。
如果感興趣的話(huà)可以來(lái)找我獲取其他的資料 想學(xué)習(xí)提升自己的私信我【JAVA架構(gòu)】獲取往期Java高級(jí)架構(gòu)資料、源碼、筆記、視頻。Dubbo、Redis、設(shè)計(jì)模式、Netty、zookeeper、Spring cloud、分布式、高并發(fā)等架構(gòu)技術(shù) 記得轉(zhuǎn)發(fā)下哦
來(lái)自同事James的一篇文章
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。