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 = []


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