2021-08-11 学习SpringMVC

Sping MVC基于MVC设计模式来实现,保证代码之间的松耦合!!!Spring MVC属于SpringFrameWork的后续产品。

主要功能:接受请求,解析请求参数;做出响应。

现在主流基于SSM三大框架开发都是在MVC上继续演化,又分为持久层DAO,业务层Service,控制层Controller。持久层用来和数据库读写ORM,业务层用来处理复杂的业务逻辑,控制层用来处理MVC的控制。

MVC

Model数据处理模型,View展示数据的视图,Controller控制层,保证上面这三部分相互独立,互不干扰,每一个部分只负责自己擅长的部分。如果某一个模块发送变化,应该尽量不影响其他两个模块。提高代码的可读性,实现程序间的松耦合,提高代码复用性!!!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XH0fEJst-1623044111711)(RackMultipart20210607-4-13lyxac_html_e58ee630c0df1991.png)]

  1.  用户发送请求至前端控制器
  2. DisspatcherServle收到请求调用HandlerMapping处理器映射器
  3. 处理器映射器找到具体的处理器(根据xml配置,注解进行查找),生产的处理器对象及处理器拦截器(有则生存),一并返回给前端控制器。
  4. 前端控制器调用handlerAdaper处理器适配器,经过适配调用具体的处理器(Controller),执行完成返回ModelAndView。处理器适配器将controller执行结果ModelAndView返回给前端控制器。
  5. 前端控制器将ModelAndView传给ViewReslover视图解析器,返回具体View。
  6. 前端控制器根据View进行渲染视图
  7. 前端控制器响应用户。

创建maven model

需求

访问链接: http://localhost:8080/car/get

得到JSON数据: {"id":718,"name":"保时捷","type":"Cayman T","color":"红色","price":641000.0}

创建启动类

package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;

@SpringBootApplication
@Controller
public class RunApp {
    public static void main(String[] args) {
        SpringApplication.run(RunApp.class);
    }

}

接受请求给出响应controller

@RestController 只能用在类上,
@RequestMapping 处理器映射器 能用在类上和方法上 严格的要求了浏览器访问方式,严格区分大小写!
package cn.tedu.controller;

import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("car")
public class CarController {
    @RequestMapping("get")
    public Car get(){
        Car car = new Car();
        car.setId(718);
        car.setName("保时捷");
        car.setType("Cayman T");
        car.setColor("红色");
        car.setPrice(641000.0);

        return car;
    }
}
package cn.tedu.pojo;

public class Car {
    private Integer id;       //718
    private String name;      //保时捷
    private String type;      //Cayman T
    private String color;     //红色
    private Double price;  //641000

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 +
                '}';
    }
}

Sping MVC请求

GET方式

向特定的资源发出请求,并返回方法,有固定的写法,而且数据有最大长度,超出就不行

public ArrayList<String> set(){
    String aa="fhbakjfhajkfh?id=1&name=张三&age=18";
    String[] split = aa.split("\\?");
    String[] split1 = split[1].split("\\&");
    ArrayList<String> objects = new ArrayList<>();
    for (int i = 0; i <split1.length ; i++) {
        String[] split2 = split1[i].split("\\=");
      objects.add(split2[1]);
    }
    return objects;
}
public String param(int id){
    return "您的请求参数"+id;
}

POST方式

向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST请求可能会导致新的资源的建立或已经资源的修改。

RESTFUL方式

  1. 需要使用注解@PathVariable来获取请求路径中的参数值,@PathVariable用来绑定值
  2. 通过{???}获取路径中传递来的值
  3. 以前GET的访问方式即将被简化成
  4. http://localhost:8080/car/insert/1/张三/
@RequestMapping("get2/{id}/{name}/{color}/{price}")
public String get1(@PathVariable Integer id,
                   @PathVariable String name,
                   @PathVariable String color,
                   @PathVariable Double price
                   ){
    return id+name+color+price;
}

POST提交数据,存入数据库,返回记录到浏览器。

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h1>学生信息管理系统MIS </h1>
		<form action="http://localhost:8080/stu/add" method="post">
		<table border="0px" cellspacing="0px" cellpadding="0px" width="325px" height="70px">
			<tr><td>姓名:</td></tr>
			<tr><td><input type="text"  placeholder="请输入姓名..." value="" name="name" style="width: 325px;"/></td></tr>
			<tr><td>年龄:</td></tr>
			<tr><td><input type="text" placeholder="请输入年龄..." value="" name="age" style="width: 325px;"/></td></tr>
			<tr><td>性别:
				<input type="radio" value="1" name="sex"/>男
				<input type="radio" value="0" name="sex"/>女
				</td></tr>
			<tr><td>爱好:
				<input type="checkbox"  name="hobby" value="ppq"/>乒乓球
				<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>入学日期:</td></tr>
				<tr><td><input type="date" name="intime"/></td></tr>
				<tr><td><input type="submit" value="保存" style="width: 40px;height: 20px;background-color: blueviolet;border: 0px;"/>
				<input type="button" value="返回"style="width: 40px;height: 20px;background-color: pink;border: 0px;"/></td></tr>
			
		</table>	
		</form>
	</body>
</html>

 POJO学生类

package cn.tedu.pojo;

import org.springframework.format.annotation.DateTimeFormat;
import java.util.Arrays;
import java.util.Date;

public class Student {
private String name;
private Integer age;
private Integer sex;
private String[] hobby;
private Integer edu;
//浏览器默认提交的日期是String类型
// 把String的日期转换成Date类型
@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 +
                '}';
    }
}

 StuController类

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.*;
import java.util.Arrays;

@RestController
@RequestMapping("stu")
public class StuController  {
    @RequestMapping("add")
    public Object add(Student stu) throws Exception  {
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cgb2106",
                "root", "root");
        PreparedStatement preparedStatement = connection.prepareStatement("insert into stu values(null,?,?,?,?,?,?)");
        preparedStatement.setObject(1,stu.getName());
        preparedStatement.setObject(2, stu.getAge());
        preparedStatement.setObject(3, stu.getSex());
        preparedStatement.setObject(4, Arrays.toString(stu.getHobby()));
        preparedStatement.setObject(5, stu.getEdu());
        preparedStatement.setObject(6,stu.getIntime());
        preparedStatement.executeUpdate();
        return stu;
    }
}

导入jdbc jar包

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
</dependency>

400错误

url中的参数类型 和 服务器需要的 参数类型不同

404错误

请求的url不存在

500错误

请求的url未绑定参数

SpringMVC常用的注解

@Controller 标识是一个Controller,Spring包扫描创建实例

@RequestMapping 请求后的映射路径

@PathVariable 标识接收单个参数

@ResponseBody 返回对象利用jackson工具类转换为json字符串

@RequestParam 参数名和请求参数名称不同时使用,可以设置默认值
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值