1.创建一个maven项目Spring-boot-demo,,结构如下:
2.配置pom.xml
4.0.0
com.example
spring-boot-demo
0.0.1-SNAPSHOT
jar
spring-boot-demo
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.5.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
com.h2database
h2
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-devtools
org.springframework.boot
spring-boot-maven-plugin
org.springframework
springloaded
1.2.6.RELEASE
3.编写启动类SpringbootDemoApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication//开启自动扫面和自动配置
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);//负责启动引动应用程序
}
}
4.编写Controller类
package com.example.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Controller注解是返回页面,比如hello.html 注意这里不要使用@RestController,这样会导致页面没法展示的问题
* 如果需要返回Json串,直接在方法上加@ResponseBody即可
*
*/
@Controller
@RequestMapping("/")
public class HelloController {
// 获取页面
@RequestMapping(value = "/hello/view", method = RequestMethod.GET)
public String hello(Model model) {
model.addAttribute("msg", "hello thymeleaf!");
Map map = new HashMap();
map.put("name", "jack");
model.addAttribute("map", map);
return "hello";
}
// 获取对象
@RequestMapping(method = RequestMethod.GET, value = "/map")
@ResponseBody // 增加注解说明是返回对象
public Map getJson() {
System.out.println(">>>>测试/boot/getMap");
Map map = new HashMap();
map.put("name", "jack");
return map;
}
}
4.编写视图层thymeleaf
Insert title here
title
5.浏览器输入 http://localhost:8080/hello/view
6.可以编写测试类SpringBootDemoApplicationTersts.java
package com.example.demo;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.demo.controller.HelloController;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDemoApplicationTests {
@Autowired
HelloController helloController;
@Test
public void testDemo() {
Map map = helloController.getJson();
Assert.assertEquals(map.get("name"), "jack");
}
@Test
public void contextLoads() {
System.out.println("-----------------------测试类------------------");
}
}