How does Spring mvc realize the connection operation with the front and back ends of the database?

  • 2021-10-15 10:28:12
  • OfStack

Spring mvc Connections to the Front and Back Ends of the Database

springboot is based on maven to manage jar package, only use springboot to download jar package only need to select, will automatically configure components in pom. xml file

Shortcut key of jar package in pom file: right-- > generate---- > depency---- > Search for jar packets

If the parameters are passed in front and back but null is returned, the name of the attribute (id, name, etc.) is written incorrectly

Startup class: Note that the startup class must be executed in the startup class. It must be started on the top of idea, otherwise it will start other startup classes and report errors


package cn.tedu;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// Startup class 
@SpringBootApplication
public class RunApp {
    public static void main(String[] args) {
        SpringApplication.run(RunApp.class);
    }
}

Create the car class (equivalent to the model layer)

Note: The construction method used here is mainly used to facilitate new


package cn.tedu.pojo;
//Model Used to encapsulate data 
public class Car {
    private int id;
    private String name;
    private double price;
    //Constructor Construct method, used for convenience new
    public Car(){}
    public Car(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
}

Use 3 ways < Object > Transmitting parameters; Note: You must have a constructor to set a value using this type

Address value of object: http://localhost: 8080/car/get


package cn.tedu.controller;
//MVC In C Layer, which is used to accept requests and respond (springmvc)
 
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController// Accept the request and put json Data return 
@RequestMapping("car")  // It is stipulated url Writing of address 
public class CarController {
// Mode 1 Value appears in the Web page 
    @RequestMapping("get")
    public Car get(){
        Car c = new Car(10,"BMW",19.9);   // Starting hook building function , What is triggered here is the parametric construction ;
        return c ;
    }
// Mode 2 Value appears in the Web page 
 @RequestMapping("save3")
    public Car save() {
        car.setAge(213);
        car.setSex(" Male ");
        car.setId(32);
         car.setPrice(32);
        return car;
    }
 Mode 3 The value in this way will be in the idea Printing in will no longer appear in web pages 
@RequestMapping("save3")
    public Car save() {
        car.setAge(213);
        car.setSex(" Male ");
        car.setId(32);
         car.setPrice(32);
        System.out.println(car);
}

The way to use return (values will appear in web pages)


package cn.tedu.controller;
 
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.naming.Name;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
 
// This is 1 A c Layer is used to receive requests and respond 
@RestController
//@RequestMapping("car")// It is stipulated url The value at this time can be written at will 
public class Controller {
 
 
   @RequestMapping("replace")
    public String replace(){
       // System.out.println(id+name+age);
 
        return "hkjds";
    }
// Mode 2 Value appears in the Web page 
 @RequestMapping("save3")
    public Car save() {
        car.setAge(213);
        car.setSex(" Male ");
        car.setId(32);
         car.setPrice(32);
        return car;
    }
 
 
}
 
}

Upload using the common get method


package cn.tedu.controller;
 
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.naming.Name;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
 
// This is 1 A c Layer is used to receive requests and respond 
@RestController
//@RequestMapping("car")// It is stipulated url The value at this time can be written at will 
public class Controller {
   
 @RequestMapping("get2")
    public void get(Integer id,String name){// Use here int Type must be assigned a value    Reference types do not have to be assigned. It is better to use reference types 
        System.out.println(id+name);
    }
    @RequestMapping("get")
               public void get(Integer id){// Use here int Type must be assigned a value    Reference types do not have to be assigned 
 
        System.out.println(id);
 
       }
 

Pass parameters in restful style

The difference between restful and common get: restful is relatively safe and simple to write

Address value of restful: http://localhost: 8080/car2/get2/10/jack/9

Other url address values://http://localhost: 8080/car/get5? id=10 & name=jack & price=9.9


package cn.tedu.controller;
 
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("car3")
// Use restful Style 
public class CarController {
 
   @RequestMapping("get2/{sex}/{id}/{name}")// The parameter order in this place must be the same as below and the address value must be 1 Sample 
public void  get2(@PathVariable String sex,
                 @PathVariable Integer id,
                 @PathVariable String name){
       System.out.println(" Data insertion succeeded "+sex+name+id);
      // System.out.println(" Data insertion succeeded "+name+id);
    }
   
 
}

spring mvc frame for parameter transmission


package cn.tedu.controller;
 
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.naming.Name;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
 
// This is 1 A c Layer is used to receive requests and respond 
@RestController
//@RequestMapping("car")// It is stipulated url The value at this time can be written at will 
public class Controller {
    // Receiving Web site parameters using frames 
    @RequestMapping("get3")
   public void  get3(Car car){
       System.out.println(car.getSex()+car.getName()+car.getId());
   }
 
}

The front and back end parameters are passed in and the data is passed into the database


package cn.tedu.controller;
 
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.events.Event;
 
import javax.naming.Name;
import java.sql.*;
import java.util.Scanner;
 
@RestController
@RequestMapping("user")
public class UserContoller {
    @RequestMapping("save")
   public void save(Integer id,String name,Integer age) throws Exception {
        System.out.println(id+name+age);
        Class.forName("com.mysql.jdbc.Driver");
        // Get a connection 
        String url ="jdbc:mysql:///cgb2104?characterEncoding=utf8&useSSL=false&amp;serverTimezone=Asia/Shanghai";
        Connection conn = DriverManager.getConnection(url,"root","root");
        // Acquisition transmitter 
//        String sql= "insert into user(id,name) values(?,?)";// Sets a value to the specified field 
        String sql= "insert into user values(?,?,?)";// Set values for all fields 
        PreparedStatement ps = conn.prepareStatement(sql);
        // To SQL Setting parameters 
        ps.setInt(1,id);// Give the first 1 A? Setting value 
        ps.setString(2,name);// Give the first 2 A? Setting value 
        ps.setInt(3,age);// Give the first 3 A? Setting value 
        // Execute SQL
        int rows = ps.executeUpdate();
        // Release resources  -- OOM(OutOfMemory)
        ps.close();
        conn.close();
    }
 

Related articles: