一、SpringBoot的主要優(yōu)點(diǎn):
1.內(nèi)置http容器(Tomcat、Jetty),最終以java應(yīng)用程序進(jìn)行執(zhí)行
2.快速整合第三方框架,無需配置文件
二、實(shí)現(xiàn)原理:
1.Maven依賴傳遞
?
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version></parent><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency></dependencies>pom文件引入依賴
?
2.SpringBoot的Web組件,默認(rèn)集成的是SpringMVC框架。SpringMVC是控制層。
?
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController// @EnableAutoConfiguration 作用 開啟自動(dòng)裝備(默認(rèn)是true)public class IndexController { // 1.在微服務(wù)情況,基本上都在類上加上@RestController 目的?返回json格式。
//2.@RestController注解相當(dāng)于@ResponseBody + @Controller合在一起的作用。如果只是使用@RestController注解Controller,則Controller中的方法無法返回jsp頁面,或者h(yuǎn)tml,配置的視圖解析器 InternalResourceViewResolver不起作用,返回的內(nèi)容就是Return 里的內(nèi)容。使用傳統(tǒng)方式返回json//@RestController 修飾的類下的所有方法,全部都是返回josn格式,這樣的話不用在方法上加上@ResponseBody @RequestMapping("/index1") public String index() throws InterruptedException { return "v6.0"; }// // 思考:如何啟動(dòng)? 使用main啟動(dòng)// public static void main(String[] args) {// // 告訴SpringBoot 程序入口 默認(rèn)端口號(hào)是8080// SpringApplication.run(IndexController.class, args);// }}
?
?
?
3.內(nèi)置Tomcat tomcat = new Tomcat() 對(duì)象
@RestController@EnableAutoConfigurationpublic class HelloController { @RequestMapping("/hello") public String index() { return "Hello World"; } public static void main(String[] args) { SpringApplication.run(HelloController.class, args); }}tomcat啟動(dòng)main方法
三、StringMVC
?
@Controller:表示這個(gè)類是SpringMVC 里的Controller,DispatchServlet會(huì)自動(dòng)掃面這個(gè)類。效果:用這個(gè)注解,通過return的String類型的數(shù)據(jù),視圖解析器可以解析jsp,html頁面,并且跳轉(zhuǎn)到相應(yīng)頁面。目的就是為了能訪問,所以是必須的。
?
@ResponseBody :可作用于類或者方法,表示該方法的返回結(jié)果直接寫入 HTTP response body 中,適用于返回JSON,XML。無法返回jsp頁面,或者h(yuǎn)tml。一般通過Ajax程序來獲取數(shù)據(jù)。一般只寫在方法上面,因?yàn)檫@個(gè)注解是為了,區(qū)別同一個(gè)類,不同的方法到底是返回頁面還是返回?cái)?shù)據(jù)!
?
@RestController: 表示 Controller ResponseBody(類上只用ResponseBody是不能被訪問的,必須要有Controller),同樣不能返回jsp和html。如果是只用于返回json的類,一般用這種。
?
@RequestMapping(“/url”):作用在 Controller的方法,表示映射地址
?
?
來源:http://www.icode9.com/content-4-229601.html聯(lián)系客服