
SpringBoot与Web开发
SpringBoot与Web开发
SpringMVC快速使用
1.基于restfulhttp接口的CURD
2.调用resthttp接口
3.通过postman调用
4.通过swagger调用
2.SpringMVC自动配置原理分析
3.定制SpringMvc的自动配置
2.通过WebMvcConfigurer进行扩展
2.Json开发
3.国际化
4.统一异常处理
4.SpringBoot的嵌入式Servlet容器
1.嵌入式Servlet容器配置修改
2.注册servlet三大组件
3.切换其他嵌入式Servlet容器
4.嵌入式Servlet容器自动配置原理SpringBoot2.3.6
5.使用外部Servlet容器
6.外部Servlet容器启动SpringBoot应用原理
SpringMVC快速使用
1.基于restfulhttp接口的CURD
1
2 /***
3 *@Author徐庶QQ:1092002729
4 *@Slogan致敬大师,致敬未来的你
5 */
6 @RestController
7 @RequestMapping("/user")
8 publicclassUserController{
9
10 @Autowired
11 UserServiceuserService;
12
13 //Rest/user/1
14 @GetMapping("/{id}")
15 publicResultgetUser(@PathVariableIntegerid){
16 Useruser=userService.getUserById(id);
17 returnnewResult<>(200,"查询成功",user);
18 }
19

20 //新增/user/add
21 @PostMapping("/add")
22 publicResultaddUser(Useruser){
23 userService.add(user);
24 returnnewResult<>(200,"添加成功");
25 }
26
27 //修改/user1
28 @PutMapping("/{id}")
29 publicResulteditUser(Useruser){
30 userService.update(user);
31 returnnewResult<>(200,"修改成功");
32 }
33
34 //修改/user1
35 @DeleteMapping("/{id}")
36 publicResulteditUser(@PathVariableIntegerid){
37 userService.delete(id);
38 returnnewResult<>(200,"删除成功");
39 }
40
41 }
2.调用resthttp接口
通过RestTemplate调用
RestTemplate是Spring提供的用于访问Rest服务的,RestTemplate提供了多种便捷访问远程Http服务的方法,传统情况下在java代码里访问restful服
务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。
适用于微服务架构下服务之间的远程调用ps:以后使用微服务架构,springcloudfeign
WebClient都可以调用远程服务,区别:webclient依赖webflux,webclient请求远程服务是无阻塞的,响应的。RestTemplate它是阻塞
的,需要等待请求响应后才能执行下一句代码
以前通过HttpClient
DELETE delete
GET
getForObject
按照指定Class返回对象
getForEntity
返回对象为ResponseEntity对象,包含了响应中的一些重要信息,
比如响应头、响应状态码、响应体等
HEAD headForHeaders

OPTIONS optionsForAllow
POST
postForLocation
postForObject
PUT put
any
支持任何请求方法类型
exchange
execute
1 @RestController
2 publicclassOrderController{
3
4 //声明了RestTemplate
5 privatefinalRestTemplaterestTemplate;
6
7 //当bean没有无参构造函数的时候,spring将自动拿到有参的构造函数,参数进行自动注入
8 publicOrderController(RestTemplateBuilderrestTemplateBuilder){
9 this.restTemplate=restTemplateBuilder.build();
10 }
11
12 @RequestMapping("/order")
13 publicStringorder(){
14 //下单需要远程访问rest服务
15
16 //基于restTemplate调用查询
17 /*ResultforObject=restTemplate.getForObject("http://localhost:8080/user/{id}",Result.class,1);
18 returnforObject.toString();*/
19
20
21 //基于restTemplate调用新增
22 /*
23
24 Useruser=newUser("徐庶","随便");
25
26 //url:请求的远程resturl
27 //object:post请求的参数
28 //Class<T>:返回的类型
29 //...Object:是@PathVariable占位符的参数
30 ResponseEntity<Result>resultResponseEntity=restTemplate.postForEntity("http://localhost:8080/use
r/add",user,Result.class);
31 System.out.println(resultResponseEntity.toString());
32 returnresultResponseEntity.getBody().toString();*/
33
34
35 //基于restTemplate调用修改
36 /*Useruser=newUser(1,"徐庶","随便");
37 //restTemplate.put("http://localhost:8080/user/add",user,Result.class);
38 HttpEntity<User>httpEntity=newHttpEntity<>(user);
39
40 ResponseEntity<Result>resultResponseEntity=restTemplate.exchange("http://localhost:8080/user/{i
d}",HttpMethod.PUT,httpEntity,Result.class,1);
41 System.out.println(resultResponseEntity.toString());
42 returnresultResponseEntity.getBody().toString();*/

43
44
45
46 //基于restTemplate调用删除
47 ResponseEntity<Result>resultResponseEntity=restTemplate.exchange("http://localhost:8080/user/{i
d}",HttpMethod.DELETE,null,Result.class,1);
48 System.out.println(resultResponseEntity.toString());
49 returnresultResponseEntity.getBody().toString();
50 }
51 }
也可以在单元测试下使用:
1 @SpringBootTest()
2 classApplicationTests{
3
4 @Test
5 voidcontextLoads(){
6 TestRestTemplaterestTemplate=newTestRestTemplate();
7 //基于restTemplate调用删除
8 ResponseEntity<Result>resultResponseEntity=
restTemplate.exchange("http://localhost:8080/user/{id}",HttpMethod.DELETE,null,Result.class,1);
9 System.out.println(resultResponseEntity.toString());
10
11 }
12
13 }
3.通过postman调用
通过MockMvc测试
MockMvc是由spring-test包提供,实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,使得测试速度
快、不依赖网络环境。同时提供了一套验证的工具,结果的验证十分方便。
SpringBoot中使用

编写测试类。实例化MockMvc有两种形式,一种是使用StandaloneMockMvcBuilder,另外一种是使用
DefaultMockMvcBuilder。测试类及初始化MockMvc初始化:
1
2 @SpringBootTest
3 @AutoConfigureMockMvc
4 classMockMvcExampleTests{
5
6 @Test
7 voidexampleTest(@AutowiredMockMvcmvc)throwsException{
8 mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("HelloWorld"));
9 }
10
11 }
0
单元测试方法:
1 @Test
2 publicvoidtestHello()throwsException{
3
4 /*
5 *1、mockMvc.perform执行一个请求。
6 *2、MockMvcRequestBuilders.get("XXX")构造一个请求。
7 *3、ResultActions.param添加请求传值
8 *4、ResultActions.accept(MediaType.TEXT_HTML_VALUE))设置返回类型
9 *5、ResultActions.andExpect添加执行完成后的断言。
10 *6、ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情
11 *比如此处使用MockMvcResultHandlers.print()输出整个响应结果信息。
12 *7、ResultActions.andReturn表示执行完成后返回相应的结果。
13 */
14 mockMvc.perform(MockMvcRequestBuilders
15 .get("/hello")
16 //设置返回值类型为utf‐8,否则默认为ISO‐8859‐1
17 .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
18 .param("name","Tom"))
19 .andExpect(MockMvcResultMatchers.status().isOk())
20 .andExpect(MockMvcResultMatchers.content().string("HelloTom!"))
21 .andDo(MockMvcResultHandlers.print());
22 }
测试结果打印:
1 FlashMap:
2 Attributes=null
3
4 MockHttpServletResponse:
5 Status=200
6 Errormessage=null
7 Headers=[Content‐Type:"application/json;charset=UTF‐8",Content‐Length:"10"]
8 Contenttype=application/json;charset=UTF‐8
9 Body=HelloTom!
10 ForwardedURL=null
11 RedirectedURL=null
12 Cookies=[]
13 2019‐04‐0221:34:27.954INFO6937‐‐‐[Thread‐2]o.s.s.concurrent.ThreadPoolTaskExecutor:Shutting
downExecutorService'applicationTaskExecutor'