Spring boot enhancement (4) -- Integration and principle analysis of spring MVC framework

He Bai Shao er 2020-11-10 23:11:51
spring boot enhancement integration principle


Spring MVC brief introduction

When designing large software systems , Business tends to be relatively complex , If all the business implementation code is entangled , There will be a lack of logic 、 Poor readability , Difficult to maintain , Change a place to pull a hair and move the whole body and other issues . In order to better solve this problem, we now often talk about hierarchical architecture design .

MVC What is it?

MVC It's a software architecture design idea , be based on MVC Architecture will be our application software layered design and Implementation , For example, it can be divided into view layers (View), Control layer (Controller), The model layer (Model), Through this layered design, our program has better flexibility and scalability . Because it simplifies a complex application , Realize that each of them performs his or her own duties , Let each person do his best . More suitable for the development of a large application .
View (View) - UI Designers design graphical interfaces , Responsible for implementing interaction with users .
controller (Controller)- Responsible for getting requests , Processing requests , In response to the results .
Model (Model) - Implement business logic , Data logic implementation .
image.png

Spring MVC summary

Spring MVC yes MVC The design idea is Spring An implementation in the framework , Based on this idea spring The framework designs some related objects , For better based on MVC Architecture handles requests and responses , Its simple structure is shown in the figure :
image.png
1. Front controller DispatcherServlet It is the entry point for all requests from the client , Responsible for request forwarding .
2. Processor mapper RequestMapping Responsible for storing requests url To the back end handler Mapping between objects .
3. Processor adapter Handler Used for processing DispatcherServlet The object of the request .
4. view resolver ViewResolver Take care of all Handler Object response result view.

Spring MVC Quick start

preparation

First step : Create project module, The basic information is shown in the figure :

image.png

The second step : Add project dependency ( Can be in module Creation time , It can also be created after ), The code is as follows :

Spring Web rely on ( Provides spring mvc Support and embed a tomcat)

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

Thymeleaf rely on ( Provided by html As a page template for parsing and operating related objects )

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

static Directory analysis and Application

static The catalogue is springboot The project was created by adding web Rely on directories created automatically later , This directory can store html、css、js、image, These resources can be started after the server , Access directly from the browser .
image

templates Directory analysis and Application

templates The catalogue is springboot The project was created by adding thymeleaf Rely on directories created automatically later , This directory needs to store some html Templates , This template page cannot be accessed directly through the browser url Visit , It needs to be based on the back-end controller , Define the page response in the method
image
among , If default.html Put it in the templates Subdirectory , You also need to configure... In the configuration file thymeleaf The prefix of

#server port
server.port=80
#spring web
spring.thymeleaf.prefix=classpath:/templates/health/
spring.thymeleaf.suffix=.html
#spring thymeleaf
spring.thymeleaf.cache=false

Definition HealthController Class to test

package com.cy.pj.health.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Controller
public class HealthController {//Handler object To deal with it DispatcherServlet Requests handed out
// Three situations
//1. Just go back to the page
//2. return json character string
//3. Return to the page and add parameters
@RequestMapping("/doPrint")
@ResponseBody
public void doPrint(HttpServletResponse response) throws Exception{
Map<String,Object> map =new HashMap<>();
map.put("username", "tony");
map.put("state", true);
//return map ;
// take map Convert data in to json Format string , The underlying implementation is as follows
ObjectMapper om=new ObjectMapper();
String jsonStr=om.writeValueAsString(map);//jackson Medium conversion json String method
System.out.println("jsonStr="+jsonStr);
// Respond the string to the client
response.setCharacterEncoding("utf-8");// Change the encoding
response.setContentType("text/html;charset=utf-8");// Tell the client our encoding format to parse the data in this way
PrintWriter pw = response.getWriter();// Write to the response stream
pw.println(jsonStr);
}
@RequestMapping("/doHealth")
public String doHealth(Model model) {
model.addAttribute("username"," Zhang San ");
model.addAttribute("state"," sub-health ");
return "default"; // The returned string is passed to the ViewResolver view resolver , Automatic analysis , Pass the parameters and present the page
}
@RequestMapping("/health.html")
@ResponseBody
// When using this annotation to describe the control method , Used to tell spring frame , The return value of this method can be in a specific format ( example json character string ) convert , To respond to clients
// Write the converted result to response In the response body of the object
//f The return value of Enfa is no longer encapsulated as ModelAndView object , It will not be handed over to the view parser for parsing , It's directly based on response Object responds to the client
public Map<String, Object> doHealth(){
Map<String,Object> map =new HashMap<>();
map.put("username", "tony");
map.put("state", true);
return map ;
}
//public ModelAndView doHealth(){// This method by DispatcherServlet Object is called by reflection
//ModelAndView mv =new ModelAndView();
//mv.setViewName("default");//viewname
//mv.addObject("username"," Li Si ");
//mv.addObject("state"," sub-health ");// It's an object , So you can pass more than strings
//return mv;
//1. The return value will be given to DispatcherServlet Object to process
//2.DispatcherServlet The object will call viewresolver Parse the results
//2.1 be based on viewname To find the corresponding view page (prefix+viewname+suffix)
//2.2 take model The data in is populated with view On the page
//2.3 Returns a value with module Data page to DispatcherServlet
//3.DispatcherServlet Will have model Data returned to the client
//public String doHealth(){
// return "default" ;// You can directly return to the page with the corresponding name
// }
}

JSON Data response

We have a business that doesn't need pages , Just convert the response data to json, And then respond to the client , How to achieve it ?
First step : Definition ResponseResult Object is used to encapsulate response data , for example :

package com.cy.pj.module.pojo;
public class ResponseResult {
private Integer code;
private String message;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

The second step : Definition JsonObjectController And how , The code is as follows :

package com.cy.pj.health.controller;
import com.cy.pj.health.pojo.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@RestController//=@Controller+@ResponseBody
public class JsonObjectController {
@RequestMapping("/doConvertResponseToJson")
public ResponseResult doConvertResponseToJson(){
ResponseResult rs=new ResponseResult();
rs.setCode(200);
rs.setMessage("OK");
return rs;
}
@RequestMapping("/doConvertMapToJson")
public Map<String,Object> doConvertMapToJson(){
Map<String,Object> map=new HashMap<>();
map.put("username"," Lau Andy ");
map.put("state",true);
return map;
}
@RequestMapping("/doPrintJSON")
public void doPrint(HttpServletResponse response)throws Exception{
Map<String,Object> map=new HashMap<>();
map.put("username"," Lau Andy ");
map.put("state",true);
// take map The data in is converted to json Format string
ObjectMapper om=new ObjectMapper();
String jsonStr=om.writeValueAsString(map);
System.out.println("jsonStr="+jsonStr);
// Respond the string to the client
// Set the encoding of the response data
response.setCharacterEncoding("utf-8");
// Tell the client , The data type to respond to is text/html, Encoded as utf-8. Please use this encoding for data presentation
response.setContentType("text/html;charset=utf-8");
PrintWriter pw=response.getWriter();
pw.println(jsonStr);
}
}

SpingMVC Request parameter data processing

We usually pass some request parameters to the server during business execution , How does the server get the parameters and inject them into our method parameters ?

package com.cy.pj.health.controller;
import com.cy.pj.health.pojo.RequestParameter;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
public class ParamObjectController {
// @GetMapping
// @PostMapping
// Restricted type on request , If the type does not match, the client will report 405 error ( Request type mismatch )
@RequestMapping("/doParam01")
public String doMethodParam(@RequestParam(required = false) String name){// Parameters of direct quantity receiving request , The parameter name should be the same as the request parameter name
// added @RequestParam(required = false) It means that you can pass the parameters, but you can not If the annotation doesn't add required Parameters Will report a mistake 400( The number of parameter types does not match )
return "request params" +name;
}
@RequestMapping("/doParam02")
public String doMethodParam(RequestParameter param){//pojo Object receives request parameters ,pojo In the object, you need to provide set Method
return "request params" +param.toString();
}
@RequestMapping("/doParam03")
public String doMethodParam(@RequestParam Map<String,Object> param){// Use map Comments are used when receiving parameters @RequestParam Describe the parameters
return "request params" +param.toString();
}
}

POJO Object mode

Definition pojo object , Used to accept client request parameters , for example :

package com.cy.pj.module.pojo;
public class RequestParameter {
private String name;
//......
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "RequestParam{" +
"name='" + name + ''' +
'}';
}
}
版权声明
本文为[He Bai Shao er]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云