一,SpringMVC
--1,概述
框架:是一个结构,框架提供了很多的类,由框架控制每个类调用的过程流程
SSM框架里,第一个S就是指SpringMVC,是一个框架
是Spring框架的一个后续产品,遵循了MVC的设计模式,保证了程序间的松耦合
SpringMVC主要作用: 1.接受请求(解析请求参数) 2.作出响应
MVC的设计模式:
M是Model模型,用来封装数据
V是View视图,用来展示数据
C是Controller控制器,用来控制浏览器如何请求,做出数据响应
好处:提高代码复用性,松耦合
--2,原理
1,前端控制器DispatcherServlet:
当浏览器发送请求成功后,充当着调度者的角色,负责调度每个组件
2,处理器映射器HandlerMapping:
根据请求的URL路径,找到能处理请求的类名和方法名
url: http://localhost:8080/hi ,找到Hello类里的hi()
3,处理器适配器HandlerAdapter:
正式开始处理业务,并把返回结果的结果交给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;
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);
}
}
3,准备一个类,补充方法(包含SpringMVC的响应)
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")
public String show(){
return "123";
}
//访问链接:http://localhost:8080/car/abc
@RequestMapping("abc")
public int show2(){
return 100;
}
/*
* SpringMVC框架除了能返回字符串,整数以外,还想返回对象信息
* {
* "id":718,"name":"保时捷","type":"Cayan T","color":"红色,"price":1000000
* }
* 创建Car类,封装属性--准备new Car*/
//访问链接:http://localhost:8080/car/Car1
@RequestMapping("Car1")
public Object show1(){
//给客户端准备数据
Car a1 = new Car(718, "保时捷", "Cayan T", "红色", 1000000);
return a1;
}
//响应数组
//访问链接:http://localhost:8080/car/pp
@RequestMapping("pp")
public int[] show3(){
int[] x = {1,2,3};
return x;
}
}
访问链接:http://localhost:8080/car/get 得到数据: 123
访问链接:http://localhost:8080/car/abc 得到数据: 100
访问链接:http://localhost:8080/car/Car1 得到:
访问链接:http://localhost:8080/car/pp 得到:
注:SpringMVC框架返回对象信息时,需要创建Car类,封装属性,如图:
package cn.tedu.mvc;
public class Car {
private int id;
private String name;
private String type;
private String color;
private double 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 String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"id=" + id +
", name='" + name + '\'' +
", type='" + type + '\'' +
", color='" + color + '\'' +
", price=" + price +
'}';
}
public Car() {
}
public Car(int id, String name, String type, String color, double price) {
this.id = id;
this.name = name;
this.type = type;
this.color = color;
this.price = price;
}
}
注:当程序修改或添加后,需要重启启动类RunApp
二,SpringMVC的响应
--1,概述
SpringMVC可以接受请求和作出响应,类型可以非常丰富
--2,测试
上述入门案例已包括SpringMVC的响应
三,SpringMVC解析get请求的参数
--1,概述
请求方式8种,常见的是 get post restful风格的数据,简化了get的写法
http://localhost:8080/car/insert?id=1&name=张三&age=18
http://localhost:8080/car/insert/1/张三/18
--2,测试
package cn.tedu.mvc;
import org.junit.Test;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//springmvc解析get请求参数
@RestController//接收请求做出响应
@RequestMapping("get")//规定了浏览器的访问方式
public class GetController {
//测试 http://localhost:8080/car/insert?id=1
@RequestMapping("param")
public String param(int id){
return "你的请求参数id="+id;
}
@RequestMapping("param1")
public String param1(int id,String name){
return "你的请求参数id="+id+",name="+name;
}
@RequestMapping("param2")
public String param2(int id,String name,double price){
return "你的请求参数id="+id+",name="+name+",price="+price;
}
@RequestMapping("param3")
public String param3(int id,String name,String type,String color,double price){
return "你的请求参数id="+id+",name="+name+",price="+price+",type="+type+",color="+color;
}
@RequestMapping("param4")
public Car param4(Car c){
return c;
}
@Test//单元测试方法
public void get1() {
String url ="http://localhost:8080/car/insert?id=1&name=张三&age=18";
String[] a = url.split("\\?")[1].split("&");
for (String s : a){
String data = s.split("=")[1];
System.out.println(data);
}
}
}
四,SpringMVC解析restful的请求参数
--1,概述
简化了get方式参数的写法
普通的get传递的参数: http://localhost:8080/car/get?id=100&name=张三
restful传递的参数: http://localhost:8080/car/get2/100/张三
--2,测试
创建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 {
//解析普通的get穿递的参数
@RequestMapping("get")
public String get(Integer id,String name){
return id+name;
}
//restful传递的参数
@RequestMapping("get2/{id}/{name}")
//{x}--通过{}访问路径中携带的参数,并交给变量x保存
public String get2(@PathVariable Integer id,
@PathVariable String name){
return id+name;
}
@RequestMapping("get3/{id}/{name}/{color}/{price}")
public String get3(@PathVariable Integer id,
@PathVariable String name,
@PathVariable String color,
@PathVariable Double price){
return id+name+color+price;
}
}
创建前端网页文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<a href="http://localhost:8080/car/get?id=100&name=张三">解析get的参数 </a>
<a href="http://localhost:8080/car/get2/100/张三">解析restful风格的参数</a>
<a href="http://localhost:8080/car/get3/100/张三/red/9.9">练习解析restful风格的参数</a>
</body>
</html>
测试
五,SpringMVC解析post的请求参数
--1,准备form表单
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body{
font-size: 17px;
background-color: lightgray;
}
/*输入框*/
.a{
width: 300px;
height: 35px;/*宽度 高度*/
font-size: 15px;/*字号*/
}
/*按钮*/
input[type="submit"]{
background-color: #0000FF;
color: white;
border-color: #0000FF;
width: 60px;
height: 30px;
}
input[type="button"]{
background-color: palevioletred;
color: white;
border-color: palevioletred;
width: 60px;
height: 30px;
}
</style>
</head>
<body>
<a href="http://localhost:8080/car/get?id=5&name=张三">解析get的参数</a>
<a href="http://localhost:8080/car/get2/3/张三">解析restful风格的参数</a>
<a href="http://localhost:8080/car/get3/3/张三/red/9.9">解析restful风格的参数</a>
<!--利用表单项服务器发送数据
默认是get提交,利用method属性修改提交方式
action属性,指定提交的位置
-->
<form method="post" action="http://localhost:8080/stu/add">
<table>
<tr>
<td>
<h2>学生信息管理系统MIS</h2>
</td>
</tr>
<tr>
<td>姓名</td>
</tr>
<tr>
<td>
<input class="a" placeholder="请输入姓名" name="name"/>
</td>
</tr>
<tr>
<td>年龄</td>
</tr>
<tr>
<td>
<input class="a" placeholder="请输入年龄" name="age" />
</td>
</tr>
<tr>
<td>
性别:(单选框)
<input type="radio" name="sex" value="1" checked="checked"/>男
<input type="radio" name="sex" value="0"/>女
</td>
</tr>
<tr>
<td>
爱好:(多选框)
<input type="checkbox" name="hobby" value="ppq" checked="checked"/>爬山
<input type="checkbox" name="hobby" 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="button" value="取消" />
</td>
</tr>
</table>
</form>
</body>
</html>
运行结果:
--2,创建Student类
package cn.tedu.pojo;
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 String类型
//报错400,需要把String类型的日期转成Data
//pattern规定了日期的格式
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date intime;
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
", hobby=" + Arrays.toString(hobby) +
", edu=" + edu +
", intime=" + intime +
'}';
}
}
--3,创建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;
}
}
--4,利用jdbc把接收到的数据入库
操作数据库,创建tb_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
)
修改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>cgb2106boot01</artifactId>
<groupId>cn.tedu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>day14</artifactId>
<!--添加jdbc的jar包依赖 -->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
</dependencies>
</project>
写jdbc代码
package cn.tedu.controller;
import cn.tedu.pojo.Student;
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;
import java.util.Arrays;
//是c层,控制层,用来接受请求和给出响应
@RestController
@RequestMapping("stu")
public class StuController {
@RequestMapping("add")
public Object add(Student s) throws Exception {
//TODO 实现入库insert-jdbc
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql:///cgb2106?characterEncoding=utf8";
Connection conn = DriverManager.getConnection(url, "root", "root");
//获取传输器
String sql = "insert into tb_student values(null,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
//给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());
//执行SQL
ps.executeUpdate();//执行增删改的SQL
System.out.println("数据插入成功!");
return s;
}
}
--5,测试
六,常见问题
404: Not Found,没找到你想访问的资源
400: 参数类型不匹配
Controller类里的方法: public void add(int a){ }
URL的方法: http://localhost:8080/add?a=jack
500: 服务器内部出错,IDEA已经抛出异常