SpringMVC 와 전단 상호작용 사례 튜 토리 얼

첫째,day 13 모듈 만 들 기
procject-오른쪽 키-new-module-maven-next-모듈 이름-finish 입력 선택
2.SpringMVC 복습
C1,수요:방문/car/get,자동차 데이터 획득
在这里插入图片描述
C2,RunApp 클래스 만 들 기

package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//   
@SpringBootApplication
public class RunApp {
    public static void main(String[] args) {
        SpringApplication.run(RunApp.class);
    }
}
C3,Car 클래스 생 성

package cn.tedu.pojo;
//Model      
public class Car {
    private int id;
    private String name;
    private double price;
    //Constructor    ,     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;
    }
}
C4,CarController 클래스 만 들 기

package cn.tedu.controller;
//MVC  C ,           (springmvc)
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//    ,  json    
@RequestMapping("car")  //   url     
public class CarController {
    @RequestMapping("get")
    public Car get(){
        Car c = new Car(10,"BMW",19.9);
        return c ;
    }
}
3.SpringMVC 분석 요청 파라미터
SpringMVC 프레임 워 크 는 요청 에 있 는 인 자 를 자동 으로 분석 할 수 있 습 니 다.자바 대상 으로 직접 봉인 할 수도 있다.스스로 파 라 메 터 를 분석 할 필요 가 없다.
C1,일반 GET 제출

package cn.tedu.controller;
//MVC  C ,           (springmvc)
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//    ,  json    
@RequestMapping("car")  //   url     
public class CarController {
    //SpringMVC          
    //http://localhost:8080/car/get5?id=10&name=BMW&price=9.9
    @RequestMapping("get5")
    public void get5(Car c){//springmvc         ,   car  
        System.out.println(c.getId()+c.getName()+c.getPrice());
    }
    //http://localhost:8080/car/get4?id=10&name=BMW
    @RequestMapping("get4")
    public void get4(Integer id,String name){
        //id     url id  ,name    url name  
        System.out.println(id+name);
    }
    //http://localhost:8080/car/get3?id=10
    @RequestMapping("get3")
//    public void get3(int id){ //       ,           ,     
    public void get3(Integer id){//       ,            null
        System.out.println(id);
    }
    //          
    public void get2(){
        String url="http://localhost:8080/car/get2?id=10&name=BMW&price=9.9";
        //  ?   ,     ,  &          [id=10,name=BMW,price=9.9]
        String[] s = url.split("\\?")[1].split("&");
        for (String ss : s) {
            String key =  ss.split("=")[0];
            String value = ss.split("=")[1] ;
        }
    }
    @RequestMapping("get")
    public Car get(){
        Car c = new Car(10,"BMW",19.9);
        return c ;
    }
}
C2,Restful 제출

package cn.tedu.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//  ,           :get/restful
@RestController
@RequestMapping("car2")
public class CarController2 {
    //1.   get        
    //    :http://localhost:8080/car2/get?id=10&name=BMW&age=10&sex=1
    @RequestMapping("get")
    public String get(Integer id,String name,Integer age,Integer sex){
//        return id+name+age+sex ;//            
        return "{'id':'"+id+"'}" ;//   json       
    }
    //2.restful        :  {}           +       {???}  
    //    :http://localhost:8080/car2/get2/10/BMW/10/1
    @RequestMapping("get2/{id}/{name}/{x}/{y}")
    public void get2(@PathVariable Integer id,
                     @PathVariable String name,
                     @PathVariable   String x,
                     @PathVariable Integer y){
        System.out.println(id);
        System.out.println(name);
        System.out.println(x);
        System.out.println(y);
    }
}
4.간단 한 전후 단 관련
C1,수요
페이지 의 a,Get 방식 으로 데 이 터 를 제출 하고 프레임 워 크 분석 파 라미 터 를 건 네 줍 니 다.
C2,html 페이지 만 들 기

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title> get          </title>
	</head>
	<body>
		<a href="http://localhost:8080/user/save?id=857&name=jack&age=666">      get</a>
		<a href="http://localhost:8080/user/save2/857/jack/666">      restful</a>
	</body>
</html>
C3,UserController 클래스 를 만 들 고 파 라 메 터 를 분석 합 니 다.

package cn.tedu.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
    //1.   get      http://localhost:8080/user/save?id=857&name=jack&age=666
    @RequestMapping("save")
    public void save(Integer id,String name,Integer age){
        System.out.println(id+name+age);
    }
    //2.   restful      http://localhost:8080/user/save2/857/jack/666
    //get restful   ?
         //get             ,restful        
        //restful       、  get       
    @RequestMapping("save2/{x}/{y}/{z}")
    public void save2(@PathVariable Integer x,
                      @PathVariable String y,
                      @PathVariable Integer z){
        System.out.println(x+y+z);
    }
}
5.JDBC 기술 을 이용 하여 요청 파 라 메 터 를 입고 합 니 다.
在这里插入图片描述
C1,jdbc 의존 추가(pom.xml 수정)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cgb2104boot01</artifactId>
        <groupId>cn.tedu</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>day13</artifactId>
    <!--  jar    -->
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
    </dependencies>
</project>
C2,사용자 테이블 준비

CREATE TABLE `user` (
  `id` int(3) default NULL,
  `name` varchar(10) default NULL,
  `age` int(2) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
C3,UserController 류 의 save()수정

package cn.tedu.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@RestController
@RequestMapping("user")
public class UserController {
    //1.   get      http://localhost:8080/user/save?id=857&name=jack&age=666
    @RequestMapping("save")
    public void save(Integer id,String name,Integer age) throws Exception {
//        System.out.println(id+name+age);
        /*         ,  jdbc    */
        //    
        Class.forName("com.mysql.jdbc.Driver");
        //    
        String url ="jdbc:mysql:///cgb2104?characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai";
        Connection conn = DriverManager.getConnection(url,"root","root");
        //     
//        String sql= "insert into user(id,name) values(?,?)";//         
        String sql= "insert into user values(?,?,?)";//       
        PreparedStatement ps = conn.prepareStatement(sql);
        // SQL    
        ps.setInt(1,id);//    ?   
        ps.setString(2,name);//    ?   
        ps.setInt(3,age);//    ?   
        //  SQL
        int rows = ps.executeUpdate();
        //     -- OOM(OutOfMemory)
        ps.close();
        conn.close();
    }
    //2.   restful      http://localhost:8080/user/save2/857/jack/666
    //get restful   ?
         //get             ,restful        
        //restful       、  get       
    @RequestMapping("save2/{x}/{y}/{z}")
    public void save2(@PathVariable Integer x,
                      @PathVariable String y,
                      @PathVariable Integer z){
        System.out.println(x+y+z);
    }
}
C4,테스트
在这里插入图片描述
在这里插入图片描述
총화
이 글 은 여기까지 입 니 다.당신 에 게 도움 을 줄 수 있 기 를 바 랍 니 다.또한 당신 이 우리 의 더 많은 내용 에 관심 을 가 져 주 실 수 있 기 를 바 랍 니 다!

좋은 웹페이지 즐겨찾기