SSM--SpringMVC入门学习

一.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=张三">解析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.项目结构

在这里插入图片描述

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 参数名和请求参数名称不同时使用,可以设置默认值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

望山。

谢谢您的打赏!!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值