spring boot初探(一)HelloWorld

建立過程如下:

一、環境準備:

  1. 安裝JDK環境,自行搜索網絡教程。

  2. 下載並安裝Maven。

  3. 下載並安裝STS。下載網址:https://spring.io/tools/sts/all/

二、搭建helloworld項目

  1.選擇創建springboot嚮導

     路徑:file->new->spring start project

     選擇WEB特性,新建一個SpringBoot項目,

  2.在pom.xml文件中存在以下依賴。

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

3.創建HelloWorldController類

@RestController
public class HelloWorldController {
    @RequestMapping("/hello")
    public String index() {
        return "Hello World";
    }
}

4.運行HelloWorldApplication類,啓動服務

5.瀏覽器輸入http://127.0.0.1:8080/hello

6.界面輸出helloworld

項目搭建成功。


三、測試

創建測試類,打印執行結果

@RunWith(SpringJUnit4Cla***unner.class)
@WebAppConfiguration
public class HelloWorldControlerTests {
    private MockMvc mvc;
    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
    }
    @Test
    public void getHello() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
}

結果:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /hello
       Parameters = {}
          Headers = {Accept=[application/json]}
Handler:
             Type = com.example.demo.HelloWorldController
           Method = public java.lang.String com.example.demo.HelloWorldController.index()
Async:
    Async started = false
     Async result = null
Resolved Exception:
             Type = null
ModelAndView:
        View name = null
             View = null
            Model = null
FlashMap:
       Attributes = null
MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=ISO-8859-1], Content-Length=[15]}
     Content type = application/json;charset=ISO-8859-1
             Body = Hello World LJZ
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章