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 .
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 :
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 :
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 .
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
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//[email protected][email protected]
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 + ''' +
'}';
}
}