Spring MVC 实例

实现前台输入数据,传入到数据库

一.前台页面代码:(html5)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
    <style type="text/css">
      body{
        font-size: 25px;


              }

    .a{
      width: 350px;
      height: 50px;
      font-size: 15px;
    }
    input[type = "submit"]{
      background-color: #67C23A;
      border-color: #00FFFF;
      color: wheat;
      width: 60px;
      height: 30px;
    }
    input[type = "reset"]{
      background-color: #9218c2;
      border-color: #ff3806;
      color: wheat;
      width: 60px;
      height: 30px;
    }

    </style>

	</head>
	<body>
    <form action="http://localhost:8080/stu/add" method="post">
      <table border="1" cellspacing="" cellpadding="">
        <tr><td>姓名</td><td><input  class = "a" type="text" name="name" placeholder="请输入姓名"/></td></tr>
        <tr><td>年龄</td><td><input type="number" name="age" class = "a" placeholder="请输入年龄" /></td></tr>
        <tr><td>性别</td><td><input type="radio" name="sex" value="1"  checked="checked" />男<input type="radio" name="sex"   value="0"/>女 </td>

        </tr>
         <tr><td>爱好</td><td><input type="checkbox" name="hobby" value="qpq" checked="checked" />乒乓球
         <input type="checkbox" name="hobby" value="ps"/>爬山
         <input type="checkbox" name="hobby" value="cg"/>唱歌</td></tr>
          <tr><td>学历</td><td><select name="edu">
            <option value="3">研究生</option>
            <option value="1">本科</option>
            <option value="2">专科</option>
          </select></td></tr>
           <tr><td>入学日期</td><td><input type="date" name="intime"  /></td></tr>
   <tr><td> <input type="submit" value="保存"/></td><td><input type="reset"  value="取消" /></td></tr>
      </table>


    </form>
	</body>
</html>

前台页面

注意:

1) action为提交到那个页面,以post方式提交,安全

2)一个标签中,最重要的是name,与value 属性,name属性表示提交数据时,数据的名字,要与后台的Model 中的对应属性的名字,类型,完全一致

3) value 属性,输入框,提交的内容就是输入的数据,而单选框,多选框,下拉框,等提交的为value属性例如

<select name="edu">
            <option value="3">研究生</option>
            <option value="1">本科</option>
            <option value="2">专科</option>
          </select>

选择的是本科,则后台获得是数据为   edu:1

二:数据库构造(mysql)

数据库代码

1 创建一个user 数据库,创建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 

)

 数据库界面

 三:后台代码(IDEA):

 后台结构

 1 启动类:

package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//标记着这是spring boot 的启动类
@SpringBootApplication
public class RunApp {
    //RunApp 必须与MVC 同包,同级
    public static void main(String[] args) {
        SpringApplication.run(RunApp.class);
    }
}

2 Student类(Model层,用来封装数据,就是pojo(封装的属性 + get/set)

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 {
    private String name;
    private Integer age;//能用引用类型,不用基本类型,因为如果前台穿空,则为null,而基本数据类型要报错500
    private Integer sex;
    private String[] hobby;//多选为字符串数组
    private Integer edu;
    @DateTimeFormat(pattern="yyyy-MM-dd")
    //网页上的日期是string 2012/8/12,注解用来转换格式,不然400错误
    private Date intime;//导入Java util包

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                ", hobby=" + Arrays.toString(hobby) +
                ", edu=" + edu +
                ", intime=" + intime +
                '}';
    }

    public Student(String name, Integer age, Integer sex, String[] hobby, Integer edu, Date intime) {

        this.name = name;
        this.age = age;
        this.sex = sex;
        this.hobby = hobby;
        this.edu = edu;
        this.intime = intime;
    }

    public Student() {
    }



    public String getName() {
        return this.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;
    }
}

注意:

1) Stuemt类中的属性与前台界面提交的属性值与属性类型要完全一致

2) 时间要用 @DateTimeFormat(pattern="yyyy-MM-dd") 来注释,是因为前台提交的为String类型,而后台为Date类型

  3 controller层

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 StudentController {
@RequestMapping("add")
    public Student abc(Student stu) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
    PreparedStatement s = c.prepareStatement("insert into tb_student values (null,?,?,?,?,?,?)");

    /*s.setString(1,stu.getName());
    s.setInt(2,stu.getAge());
    s.setInt(3,stu.getSex());
    s.setString(4, String.valueOf(stu.getHobby()));
    s.setInt(5,stu.getEdu());
    s.setDate(6, (Date) stu.getIntime());*/
    s.setObject(1,stu.getName()); //使用多态,
    s.setObject(2,stu.getAge());
    s.setObject(3,stu.getSex());
    //数据库中没有数组的概念,不能直接存入数据库,
    s.setObject(4, Arrays.toString(stu.getHobby()));
    s.setObject(5,stu.getEdu());
    s.setObject(6, stu.getIntime());
    int i = s.executeUpdate();
    if(i == 1){
        System.out.println("添加成功");
    }else{
        System.out.println("添加失败");
    }


    return stu;

}
}

注意:

1) 使用多态,方便 但是可能出现一些错误,例如向数据库存放数组, 只能:使用  :s.setObject(4, Arrays.toString(stu.getHobby()));   因为数据库中没有数组的概念

4 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>cgb2106boot01</artifactId>
        <groupId>cn.tedu</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>dat14</artifactId>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
    </dependencies>
</project>

五:使用:启动html,输入数据

六: 常用注解

@RestController  发出请求,做出响应,写在类上

@RequestMapping("stu") 写在方式以类上   指定url 的写法

@PathVariable 获得路径中变量的值  post方式提交使用

七: POST 提交数据方式

package cn.tedu.controller;

import org.junit.Test;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController//收到请求,发出相应
@RequestMapping("car")//指定url 的写法
public class Test1 {
    //http://localhost:8080//getc/param?id=1&name="张三"
    @RequestMapping("get1")
    @Test
    //直接输入http://localhost:8080//car/get1 相当于所有的的值,都没有赋值 基本数据类型不赋值会报错,而引用类型不赋值会给null
    public String get1(Integer id,String name){
        return id + name;
    }
    //http://localhost:8080/bb/bb1/100/张三
    // {x}--通过{} 获取访问路径中的参数,并交给变量x保存
    @RequestMapping("get2/{id}/{name}")//获取get2 之后的值
    //@PathVariable 获得路径中变量的值
    public String get2(@PathVariable Integer id,@PathVariable String name){
        return id + name;
    }
    @RequestMapping("get3/{id}/{name}/{color}/{jg}")
    public String get3(@PathVariable Integer id,@PathVariable String name,@PathVariable String color,@PathVariable Double jg){
        return id + name + color + jg;

    }

}

八:GET 提交数据方式

package cn.tedu.mvc;
/**
 * 错误400 找到了页面 但参数类型不匹配
 * 错误404 找不到页面
 * 错误500 idea 内部出现了错误
 */

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Spring MVC 解析get请求参数
 */
@RestController//接受请求,做出相应
@RequestMapping("getc")//规定了浏览器的访问方式
public class GetController {
    //http://localhost:8080//getc/param?id=1  form表单get提交方法

    //http://localhost:8080//getc/param?id=1&name="张三"
    //http://localhost:8080//getc/param?id=1   //您的请求参数里id =1您的请求参数里name =null
    //http://localhost:8080//getc/param?id=1&name="张三"&pass="撒"  只能id,name 的情况下,也能解析到id,name

    @RequestMapping("param1")
    public Car param(Car car){//将对象所有属性都获得
        return car;
    }



/*    @RequestMapping("param")
    public String param(int id,String name){//参数列表必须一致 不能乱写
        return "您的请求参数里id =" + id + "您的请求参数里name =" + name;
    }*/



   /* @Test
    public void jq(){
        //http://localhost:8080/car/insert?id=1&name=张三&age=18 解析数据
        String a = "http://localhost:8080/car/insert?id=1&name=张三&age=18";
        String[] a1 = a.split("\\?");
        System.out.println(Arrays.toString(a1));
        String[] a2 = a1[1].split("\\&");
        System.out.println(Arrays.toString(a2));

        for(int i = 0;i < a2.length;i++){
            String[] a3 = a2[i].split("\\=");// \\转义字符
            System.out.println(a3[1]);
        }


    }*/

    //数组方式
/* @RequestMapping("getj")
    public String[] jq(){
        //http://localhost:8080/car/insert?id=1&name=张三&age=18 解析数据
        String a = "http://localhost:8080/car/insert?id=1&name=张三&age=18";
        String[] a1 = a.split("\\?");
        System.out.println(Arrays.toString(a1));
        String[] a2 = a1[1].split("\\&");
        System.out.println(Arrays.toString(a2));
        //string方式
        String[] a4 = new String[a2.length];
        for(int i = 0;i < a2.length;i++){
            String[] a3 = a2[i].split("\\=");// \\转义字符
            System.out.println(a3[1]);
            a4[i] = a3[1];
        }
return a4;

    }*/

//集合方式
 /*   @RequestMapping("getj")
    public ArrayList<String> jq(){
        //http://localhost:8080/car/insert?id=1&name=张三&age=18 解析数据
        String a = "http://localhost:8080/car/insert?id=1&name=张三&age=18";
        String[] a1 = a.split("\\?");
        System.out.println(Arrays.toString(a1));
        String[] a2 = a1[1].split("\\&");
        System.out.println(Arrays.toString(a2));
        //集合
        ArrayList<String> a4 = new ArrayList<>();
        for(int i = 0;i < a2.length;i++){
            String[] a3 = a2[i].split("\\=");// \\转义字符
            System.out.println(a3[1]);
            a4.add(a3[1]);
        }
        return a4;

    }
*/

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值