文章目錄
-
- 一.SpringMVC架構
-
- 1.概述
- 2.原理
-
- (1)前端控制器DispatcherServlet:
- (2)處理器映射器HandlerMapping:
- (3)處理擴充卡HandAdaptor:
- (4)視圖解析器ViewResolver:
- (5)視圖渲染view
- 3.建立Module
- 4.入門案例
-
- (1)導入jar包(被Spring Boot整合好了)
- (2)準備一個啟動類RunApp
- (3)準備一個類,補充方法
- 二.SpringMVC的響應
-
- 1.概述
- 2.案例:展示汽車資料
- 3.測試
- 三.SpringMVC解析get請求的參數
-
- 1.概述
- 2.測試
- 3.常見問題
- 四.SpringMVC解析restful的請求參數
-
- 1.概述
- 2.測試
- 五.SpringMVC解析post的請求參數
-
- 1.項目結構
- 2.準備form表單
- 3.準備Student類
- 4.準備StudentController類
- 5.利用jdbc把接受到的參數入庫
- 6.修改pom.xml檔案,添加jdbc的jar包的坐标
- 7.寫jdbc的代碼
- 8.測試
- 9.總結
- MVC和SSM的關系
一.SpringMVC架構
Spring MVC屬于SpringFrameWork的後續産品,已經融合在Spring Web Flow裡面。Spring 架構提供了建構 Web 應用程式的全功能 MVC 子產品。
SpringMVC就是基于MVC設計模式來實作的。(松耦合)
POJO就是Model層,JSP就是視圖層,Controller就是控制層。
1.概述
架構:是一個結構,架構提供了很多的類,由架構控制每個類調用的過程流程
SSM架構裡,第一個S就是指SpringMVC,是一個架構,是Spring架構的一個後續産品,,遵循了MVC的設計模式,保證了程式間的松耦合,
SpingMVC主要作用:1.接收請求(解析請求參數)2.做出響應
MVC設計模式

M是Model模型,用來封裝資料
V是View視圖,用來展示資料
C是Controller控制器,用來控制浏覽器如何請求,做出資料響應
好處: 提高代碼的複用性 , 松耦合
MVC模型
用來進行分層的結構,這樣代碼分離結構清晰,各層代碼,各司其職,易于開發大型項目。
MVC(Model模型、View視圖、Control控制層),将軟體進行分層達到松耦合的效果。
通用的軟體程式設計思想, 在MVC設計模式中認為, 任何軟體都可以分三層:控制層(Controller)、資料處理模型(Model)、負責展示資料的視圖(View)。
在MVC設計思想中要求一個符合MVC設計思想的軟體應該保證上面這三部分互相獨立,互不幹擾,每一個部分隻負責自己擅長的部分。如果某一個子產品發生變化,應該盡量做到不影響其他兩個子產品。提高代碼的可讀性,實作程式間的松耦合、提高代碼複用性。
耦合性:之間的依賴關系
2.原理
(1)前端控制器DispatcherServlet:
當浏覽器發送請求成功後,充當排程者的角色,負責排程每個元件
(2)處理器映射器HandlerMapping:
根據請求的url路徑,找到能處理請求的類名和方法名
URL:http://localhost:8080/hi 找到HelloController類裡的hi()
(3)處理擴充卡HandAdaptor:
正式開始處理業務,并把傳回結果的結果交給DispatcherServlet
(4)視圖解析器ViewResolver:
找到正确的,能展示資料的視圖,準備展示資料
(5)視圖渲染view
展示資料
3.建立Module
選中Project-右鍵-New-Module-選擇Maven-next-輸入Module的名字-next-finish
4.入門案例
(1)導入jar包(被Spring Boot整合好了)
(2)準備一個啟動類RunApp
package cn.tedu.mvc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//标記着這是springboot的啟動類
@SpringBootApplication
public class RunApp {
public static void main(String[] args) {
SpringApplication.run(RunApp.class);//運作目前類
}
}
(3)準備一個類,補充方法
通路連結:http://localhost:8080/car/get
得到資料:123
package cn.tedu.mvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//完成springmvc的角色,接受請求和給出響應
//是MVC設計模式裡的C控制器,接受請求和給出響應
@RestController
//标記着這個類是Controller是一個控制器+接受請求
@RequestMapping("car")//規定了url怎麼通路這個類
public class HelloController {
//測試: http://localhost:8080/car/get
@RequestMapping("get")//規定了url怎麼通路這個方法
public String show(){
return "123";
}
}
二.SpringMVC的響應
1.概述
SpringMVC可以接受請求,和做出響應資料,類型可以非常豐富
2.案例:展示汽車資料
package cn.tedu.mvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//完成springmvc的角色,接受請求和給出響應
//是mvc設計模式裡的c控制器,接受請求和給出響應
@RestController//标記這這個類是Controller是一個控制器
@RequestMapping("car")//規定了url怎麼通路這個類
public class HelloController {
//通路連結:http://localhost:8080/car/get
@RequestMapping("get")//規定了url怎麼通路這個方法
public String show(){
return "123";
}
//通路連結:http://localhost:8080/car/C
@RequestMapping("C")
public int show2(){
return 100;
}
//SpringMVC架構除了能傳回字元串,整數以外,還想傳回對象資訊
//{"id":718,"name":"保時捷","type":"Cayman T","color":"紅色","price":641000.0}
@RequestMapping("get2")
public Car get(){
Car c = new Car();
//給用戶端浏覽器準備資料
c.setId(718);
c.setName("保時捷");
c.setType("Cayman");
c.setColor("紅色");
c.setPrice(641000.0);
return c;
}
@RequestMapping("arr")
public int[] arr(){
int[] a = {1,2,3,4};
return a;
}
}
3.測試
啟動伺服器,打開浏覽器,通路正确的URL位址
三.SpringMVC解析get請求的參數
1.概述
當用戶端打開浏覽器要通路伺服器時,可能會帶着一些http請求參數過來.
請求方式總共有8種,重點是兩種方式:GET方式和POST方式.
restful風格的資料,用來簡化了get的寫法
http://localhost:8080/car/insert?id=1&name=張三&age=18
http://localhost:8080/car/insert/1/張三/18
GET方式
向特定的資源送出請求,并傳回實體.有固定的寫法.而且資料有最大長度,超出就不行
例如:
http://localhost:8080/car/insert?id=1&name=張三&age=18
POST方式
向指定資源送出資料進行處理請求(例如送出表單或者上傳檔案)。資料被包含在請求體中。POST請求可能會導緻新的資源的建立和/或已有資源的修改。
2.測試
package cn.tedu.mvc;
import org.junit.Test;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
//SpringMVC解析get請求參數
//400參數類型不比對
//404找不到
//500内部錯誤
@RestController//接受請求做出響應
@RequestMapping("get")//規定了浏覽器的通路方式
public class GetController {
//測試http://localhost:8080/get/param?id=1
@RequestMapping("param")
public String param( int id){
return "您的請求參數裡id="+id;
}
@RequestMapping("param2")
public void param2(int id,String name){
System.out.println(id);
System.out.println(name);
}
@RequestMapping("nm")
public String nm(int id,String name){
return "您的請求參數裡id="+id+",name="+name ;
}
@RequestMapping("param3")
public void param3(int id,String name,int age){
System.out.println(id);
System.out.println(name);
System.out.println(age);
}
@RequestMapping("param4")
// public String param4(int id,String name,String type,String color,double price){
// return id+name+type+color+price;}
public Car param4(Car c){//直接用對象接受參數,架構會自動封裝屬性的值
return c;
}
@Test//單元測試方法
public void get1(){
//http://localhost:8080/car/insert?id=1&name=張三&age=18
String url="http://localhost:8080/car/insert?id=1&name=張三&age=18";
//1.舊方法
// String[] a = url.split("\\?");
// System.out.println(a[1]);
// String[] b = a[1].split("&");
// for(int i =0;i<b.length;i++){
// String[] c =b[i].split("=");
// Sy
// stem.out.println(c[1]);
// }
//2.簡寫
// String[] a = url.split("\\?")[1].split("&");
// for(String s: a){
// String data = s.split("=")[1];
// System.out.println(data);
// }
}
}
3.常見問題
404:NOT FOUND,沒找到你想通路的資源
400:參數類型不比對
Controller類裡的方法:public void add(String name){}
URL的方法:http:localhost:8080/add?a=jack
500:伺服器内部出錯,IDEA已經抛出異常了
四.SpringMVC解析restful的請求參數
1.概述
簡化了get方式參數的寫法
普通的get傳遞的參數 http://localhost:8080/car/get?id=100&name=張三
restful傳遞的參數 http://localhost:8080/car/get2/100/張三
2.測試
建立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);
}
}
建立CarController類
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("car")
public class CarController {
//注意1:: 參數清單裡的參數類型,最好使用引用類型,
//如果浏覽器沒有傳值過來就用預設值,但使用基本類型會抛異常的
//解析普通的get傳遞的參數
//http://localhost:8080/car/get?id=100&name=張三
@RequestMapping("get")
// public String get(int id,String name){
public String get(Integer id,String name){
return id+name ;
}
//解析restful傳遞的參數:簡化了get方式參數的寫法
//http://localhost:8080/car/get2/100/張三
@RequestMapping("get2/{id}/{name}")
//{x}--通過{}擷取通路路徑中攜帶的參數,并且交給變量x儲存
//@PathVariable -- 擷取{}中間變量的值
public String get2(@PathVariable Integer id,
@PathVariable String name){
return id+name;
}
}
建立前端網頁檔案
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<a href="http://localhost:8080/car/get?id=100&name=張三" target="_blank" rel="external nofollow" >解析get的參數 </a>
<a href="http://localhost:8080/car/get2/100/張三" target="_blank" rel="external nofollow" >解析restful風格的參數</a>
<a href="http://localhost:8080/car/get3/100/張三/red/9.9" target="_blank" rel="external nofollow" >練習解析restful風格的參數</a>
</body>
</html>
測試
五.SpringMVC解析post的請求參數
1.項目結構
2.準備form表單
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>學生資訊表單</title>
<style >
body{
font-size: 20px;/*字型大小*/
background-color: #ebfaee;/*背景色*/
}
/*輸入框*/
.a{
width: 320px;/*寬度*/
height: 40px;/* 高度*/
font-size: 20px;/*字型*/
}
/*儲存按鈕*/
input[type="submit"]{
background-color: #00AAFF;/*背景色 */
color:white ;/*字的顔色*/
border-color: #00AAFF;/*邊框顔色*/
width: 60px;/*寬度*/
height: 30px;/*高度*/
}
/*取消按鈕*/
input[type="reset"]{
background-color: #ff557f;/*背景色 */
color:white ;/*字的顔色*/
border-color: #ff557f;/*邊框顔色*/
width: 60px;/*寬度*/
height: 30px;/*高度*/
}
</style>
</head>
<body>
<form action="http://localhost:8080/stu/add" method="post">
<table >
<h1>學生資訊管理系統MIS</h1>
<tr>
<td >
姓名:
</td>
</tr>
<tr>
<td >
<input class="a"type="text"name="name"placeholder="請輸入姓名……" />
</td>
</tr>
<tr>
<td >
年齡:
</td>
</tr>
<tr>
<td >
<input class="a" type="number"name="age" placeholder="請輸入年齡……"/>
</td>
</tr>
<tr>
<td>性别:
<input type="radio" name="sex"value="1"checked="checked" />男
<input type="radio"name="sex"value="0" />女
</td>
</tr>
<tr>
<td class="b">愛好:
<input type="checkbox" name="hobby" value="ppq"checked="checked" />乒乓球
<input type="checkbox" name="hpbby" value="ps" />爬山
<input type="checkbox" name="hobby" value="cg" />唱歌
</td>
</tr>
<tr>
<td>
學曆:
<select name="edu">
<option value ="1">大學</option>
<option value ="2">研究所學生</option>
<option value ="3">博士</option>
</select>
</td>
</tr>
<tr>
<td>
入學日期:
<input type="date" name="intime" />
</td>
</tr>
<tr>
<td>
<input type="submit"value="儲存" />
<input type="reset" value="取消" />
</td>
</tr>
</table>
</form>
</body>
</html>
3.準備Student類
package cn.tedu.jojo;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Arrays;
import java.util.Date;
//是model層,用來封裝資料,就是一個pojo(封裝的屬性+get/set)
public class Student {
//屬性(成員變量):變量類型 變量名
//送出資料的類型 頁面上name屬性的值
private String name;
private Integer age;//應用類型比基本類型強,避免一些異常
private Integer sex;
private String[] hobby;
private Integer edu;
//浏覽器上送出的日期預設是2021/8/12
//@DateTimeFormat把String的日期轉成date日期
//pattern屬性規定了日期的格式y表示年(四位數),M表示月(兩位數),d表示天(兩位數)
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date intime;
//toString
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", hobby=" + Arrays.toString(hobby) +
", edu=" + edu +
", intime=" + intime +
'}';
}
//get set
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public Integer getEdu() {
return edu;
}
public void setEdu(Integer edu) {
this.edu = edu;
}
public Date getIntime() {
return intime;
}
public void setIntime(Date intime) {
this.intime = intime;
}
}
4.準備StudentController類
package cn.tedu.controller;
import cn.tedu.pojo.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//是C層,控制層,用來接受請求和給出響應
@RestController
@RequestMapping("stu")
public class StudentController {
@RequestMapping("add")
public Object add(Student s){
//TODO 實作入庫insert
return s;
}
}
5.利用jdbc把接受到的參數入庫
操作cgb2106的庫, 建立tb_student表(參考Student類)
CREATE TABLE tb_student(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50),
age INT,
sex INT,
hobby VARCHAR(100),
edu INT,
intime DATE
)
6.修改pom.xml檔案,添加jdbc的jar包的坐标
<?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>cgb2106boot03</artifactId>
<groupId>cn.tedu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>day14</artifactId>
<dependencies>
<!--添加jdbc的jar包依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
</dependencies>
</project>
7.寫jdbc的代碼
package cn.tedu.controller;
import cn.tedu.jojo.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.*;
import java.util.Arrays;
//是c層,用來接受請求和給出響應
@RestController
@RequestMapping("stu")
public class StudentController {
@RequestMapping("add")
public Object add(Student s) throws Exception {
//TODO 利用jdbc,實作入庫insert
//1.注冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2.擷取連接配接
String url ="jdbc:mysql://localhost:3306/cgb2106?characterEncoding=utf8";
Connection conn = DriverManager.getConnection(url,"root","root");
//3.擷取傳輸器
String sql="insert into tb_student values(null,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
//4.給sql設定參數
ps.setObject(1,s.getName());
ps.setObject(2,s.getAge());
ps.setObject(3,s.getSex());
//s.getHobby()得到一個數組,不能直接存入資料庫,需要變成串入庫
ps.setObject(4, Arrays.toString(s.getHobby()));
ps.setObject(5,s.getEdu());
ps.setObject(6,s.getIntime());
//5.執行sql
ps.executeUpdate();//執行增删改的sql
System.out.println("資料插入成功!!");
return s;
}
}
8.測試
9.總結
MVC和SSM的關系
SpringMVC常用的注解
@Controller 辨別是一個Controller,Spring包掃描建立執行個體
@RequestMapping 請求後的映射路徑
@PathVariable 辨別接收單個參數
@ResponseBody 傳回對象利用jackson工具類轉換為json字元串
@RequestParam 參數名和請求參數名稱不同時使用,可以設定預設值