1. 程式人生 > >Spring_boot入門(1)

Spring_boot入門(1)

ppi lease 結構 有關 tomcat jos already ase rod

Spring boot 將很多東西都集成在一起了,搭建maven項目的時候只需要引入很少的依賴就可以實現項目的搭建。

1.搭建maven項目結構

2.引入Spring boot 依賴 直接去官網找就可以了,還有例子說明

3.pom.xml 導入依賴包,最開始用的1.5.10的版本不知道為啥main方法啟動的時候tomcat無法啟動,後來換了版本就可以了

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <
artifactId>spring-boot-starter-web</artifactId> <version>1.5.7.RELEASE</version> </dependency> </dependencies>

4.main方法啟動Spring boot 啟動類始用 @SpringBootApplication 註解

package di.bao;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FirstAPP { public static void main(String[] args) { SpringApplication.run(FirstAPP.class, args); } }

5.tomcat啟動之後就可以直接訪問了,直接訪問8080端口會出現錯誤頁面,編寫一個controller,始用@Controller 註解,訪問8080/nihao,頁面出現方法返回值。

package di.bao;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody; @Controller public class NiController { @GetMapping("/nihai") @ResponseBody public String hello() { return "shi jie ni hao!"; } }

6.rest接口,返回josn 格式字符串 :創建一個類,編寫controller,訪問http://localhost:8080/student/1 ,頁面:{"name":"zhangsan","id":1}

package di.bao;

public class Student {

    private String  name;
    private int id;
   
    public Student() {
        
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    
    
}
package di.bao;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class JosnController {
    /**
     * value 路徑   method 訪問方法  produces 產出什麽
     * @param id
     * @return
     */
    @RequestMapping(value = "/student/{id}", method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Student hello(@PathVariable int id) {
        Student student = new Student();
        student.setId(id);;
        student.setName("zhangsan");
        return student;
    }
}

註意:再次使用main方法啟動的時候一定要先將上一次啟動的先關閉,否則會出現端口占用出現java.net.BindException: Address already in use: bind 異常。

命令行:netstat -ano|findstr "8080"

技術分享圖片

命令行:輸入tasklist 查看11000是哪個進程

技術分享圖片

win7的話直接在任務管理器裏面把占用端口的程序關掉就可以了。

由於系統換了win10,win10的任務管理器有點不一樣,找了半天也沒找到這個進程,索性把java相關的 都關掉了,結果還是沒用,

後來發現在應用 eclipse下面還有一個java有關的,關掉那個就可以正常重啟了

技術分享圖片

Spring_boot入門(1)