這個不涉及的前端頁面,不會跳轉頁面。在瀏覽器訪問時僅顯示返回的內容。
再說之前先列出兩個參考IDEA下從零開始搭建SpringBoot工程和SpringBoot入門系列:第一篇 Hello World,第二篇的這個博主寫了一系列的,不過由於用的eclipse只做參考。
首先File-new-project;
選擇maven,然後中上那裏記得打鉤。然後點next,groupID 和artifactId自己隨便輸入
點next,輸入文件名,點擊finish。這樣一個maven就創建好了。
然後在pom.xml進行配置,
<!-- spring boot-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<!-- 引入Web模塊 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
</dependencies>
之前描述的有點亂,現在我重新整理一下語言。
網上能找到的例子裏很多main方法和請求是在同一個實體類裏的,類似下面這種。訪問地址是localhost:8080/
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
當時的想法是如果啓動的main和需要訪問的url不在同一個類裏呢,要怎麼處理呢首先定義一個application類,也就是啓動的main
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
* Created by jianbao on 2017/6/7.
*/
@SpringBootApplication
@ComponentScan(basePackages = "com")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
@ComponentScan告訴它要掃描哪個包
然後是controller層。新建了一個HelloController。這裏的兩個註解和最上面那個Example是一樣的。
@EnableAutoConfiguration 用於自動配置。簡單的說,它會根據你的pom配置(實際上應該是根據具體的依賴)來判斷這是一個什麼應用,並創建相應的環境
@RestController相當於@ResponseBody + @Controller合在一起的作用
@RestController
@EnableAutoConfiguration
public class HelloController {
@RequestMapping("/say")
String home() {
System.out.println("jinru");
return "Hello World!";
}
@RequestMapping("/hello/{name}")
//方法里加上@PathVariable可以讀出參數
String hello(@PathVariable String name){
return "hello"+name;
}
}
基本上這樣一個程序就可以運行起來了,在main方法那裏運行。
這樣即使main和controller不在一起,也可以訪問。然後通過瀏覽器訪問localhost:8080/say或者localhost:8080/hello/name.