一、springboot入门
1.maven构建项目
访问http://start.spring.io/,下载springboot示例项目,导入eclipse。(Existing Maven Projects)
2.项目结构
如上图所示,Spring Boot的基础结构共三个文件:
-
src/main/java 程序开发以及主程序入口
-
src/main/resources 配置文件
-
src/test/java 测试程序
代码结构
-
1、Application.java 建议放到跟目录下面,主要用于做一些框架配置
-
2、domain目录主要用于实体(Entity)与数据访问层(Repository)
-
3、service 层主要是业务类代码
-
4、controller 负责页面访问控制
3.引入web模块
a、pom.xml中添加支持web的模块:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
pom.xml文件中默认有两个模块:
spring-boot-starter
:核心模块,包括自动配置支持、日志和YAML;
spring-boot-starter-test
:测试模块,包括JUnit、Hamcrest、Mockito。
b.编写controller内容
package com.example.demo.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.domain.User; @RestController public class HelloWorldController { @RequestMapping("/hello") public String index(){ return "Hello World"; } /* @RequestMapping("/getUser") public User getUser(){ User user = new User(); user.setUserName("David"); user.setPassWord("123456"); return user; }*/ }
启动主程序,打开浏览器访问http://localhost:8080/hello
其中的注解@RestController的意思是controller中的方法都已json格式输出,不需要写jackjson等配置。
4.单元测试
package com.example.demo; import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.example.demo.controller.HelloWorldController; 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"] Body = <no character encoding set> Session Attrs = {} Handler: Type = com.example.demo.controller.HelloWorldController Method = public java.lang.String com.example.demo.controller.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:"11"] Content type = application/json;charset=ISO-8859-1 Body = Hello World Forwarded URL = null Redirected URL = null Cookies = []