SpringMVC 와 전단 상호작용 사례 튜 토리 얼
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&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,테스트총화
이 글 은 여기까지 입 니 다.당신 에 게 도움 을 줄 수 있 기 를 바 랍 니 다.또한 당신 이 우리 의 더 많은 내용 에 관심 을 가 져 주 실 수 있 기 를 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
ssm 프레임워크 업로드 이미지 로컬 및 데이터베이스에 저장 예시본고는 ssm 프레임워크 업로드 이미지를 로컬과 데이터베이스에 저장하는 예시를 소개하고 주로 Spring+SpringMVC+MyBatis 프레임워크를 사용하여 ssm 프레임워크 업로드 이미지의 실례를 실현했다. 구체...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.