springboot 简单练习

  • 数据库搭建
create database if not exists mybatis;
use mybatis;

CREATE TABLE `student1` (
`id` int(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`sname` varchar(255) not null comment '姓名',
`sex` varchar(255) default '男' comment '性别',
`birthday` datetime default null comment '出生日期',
`hobbies` varchar(255) default null comment '爱好',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
  • pom.xml
<!--创建springboot,自动勾选好web,mybatis,mysql,thymeleaf   最后看缺哪些依赖-->
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.80</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
  • 搭建springboot包格式

  • 创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private Integer id;
    private String sname;
    private String sex;
    private Date birthday;
    private String hobbies;
}
  •  application.properties文件  
spring.datasource.username=root
spring.datasource.password=123456
# THYMELEAF (ThymeleafAutoConfiguration)
# 开启模板缓存(默认值: true )
spring.thymeleaf.cache=false
# 检查模板是否存在,然后再呈现
spring.thymeleaf.check-template=true
# 检查模板位置是否正确(默认值 :true )
spring.thymeleaf.check-template-location=true
#Content-Type 的值(默认值: text/html )
spring.thymeleaf.content-type=text/html
# 开启 MVC Thymeleaf 视图解析(默认值: true )
spring.thymeleaf.enabled=true
# 模板编码
spring.thymeleaf.encoding=UTF-8
# 要被排除在解析之外的视图名称列表,⽤逗号分隔
spring.thymeleaf.excluded-view-names=
# 要运⽤于模板之上的模板模式。另⻅ StandardTemplate-ModeHandlers( 默认值: HTML5)
spring.thymeleaf.mode=HTML5
# 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ )
spring.thymeleaf.prefix=classpath:/templates/
# 在构建 URL 时添加到视图名称后的后缀(默认值: .html )
spring.thymeleaf.suffix=.html
#date格式
spring.mvc.format.date=yyyy-MM-dd
  • 搭建mybatis
  • StudentMapper接口
package com.my.mapper;

import com.my.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface StudentMapper {
//    获取所有的student
    List<Student> findAll();

//    根据id查找
    Student findById(Integer id);

//    根据名字模糊查询
    List<Student> likeStudent(String sname);

//    添加数据
    int insertTo(Student student);

//    修改数据
    int updateTo(Student student);

//    根据id删除数据
    int deleteTo(@Param("id") Integer id);
}
  • 在resources新建mappers目录,并建studentMapper.xml文件
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.my.mapper.StudentMapper">
    <insert id="insertTo">
        insert into student1(sname,sex,birthday,hobbies) value (#{sname},#{sex},#{birthday},#{hobbies})
    </insert>
    <update id="updateTo">
        update student1 set sname=#{sname},sex=#{sex},birthday=#{birthday},hobbies=#{hobbies} where id=#{id}
    </update>
    <delete id="deleteTo">
        delete from student1 where id=#{id}
    </delete>

    <select id="findAll" resultType="com.my.pojo.Student">
        select * from student1
    </select>
    <select id="findById" resultType="com.my.pojo.Student">
        select * from student1 where id=#{id}
    </select>
    <select id="likeStudent" resultType="com.my.pojo.Student">
        select * from student1 where sname like  concat('%',#{sname},'%')
    </select>

</mapper>
  • 主启动类,配置MapperScan
package com.my;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.my.mapper")
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

}@MapperScan(basePackages = "com.my.mapper")
  • Service层
  • StudentService接口
package com.my.service;

import com.my.pojo.Student;

import java.util.List;

public interface StudentService {
    List<Student> findAll();
    List<Student> likeStudent(String sname);
    int insertTo(Student student);
    int updateTo(Student student);
    int deleteTo(Integer id);
    Student findById(Integer id);
}
  • 实现类StudentServiceImpl
package com.my.service;

import com.my.mapper.StudentMapper;
import com.my.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService{

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Student> findAll() {
        List<Student> students=studentMapper.findAll();
        return students;
    }

    @Override
    public  List<Student> likeStudent(String sname) {
        List<Student> students=studentMapper.likeStudent(sname);
        return students;
    }

    @Override
    public int insertTo(Student student) {
        int i=studentMapper.insertTo(student);
        return i;
    }

    @Override
    public int updateTo(Student student) {
        int i=studentMapper.updateTo(student);
        return i;
    }

    @Override
    public int deleteTo(Integer id) {
        int i=studentMapper.deleteTo(id);
        return i;
    }

    @Override
    public Student findById(Integer id) {
        Student student=studentMapper.findById(id);
        return student;
    }
}
  • controller层
  • StudentController
package com.my.controller;

import com.alibaba.fastjson.JSON;
import com.my.pojo.Student;
import com.my.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
public class StudentController {

    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private StudentService studentService;

    @RequestMapping("/all")
    public String findAll(Model model){
        List<Student> list=studentService.findAll();
        model.addAttribute("students",list);
        return "studentList";
    }


    @RequestMapping("/like")
    @ResponseBody
    public String likeStudent(HttpServletRequest request){
        return studentService.likeStudent("张").toString();
    }

    @RequestMapping("/add")
    public String add(){
        return "addStudent";
    }

    @RequestMapping("/insertTo")
    public String insertTo(HttpServletRequest request) throws ParseException {
        Student student=new Student();
        student.setSname(request.getParameter("name"));
        student.setSex(request.getParameter("sex"));
        student.setBirthday(sf.parse(request.getParameter("birthday")));
        student.setHobbies(request.getParameter("hobbies"));
        studentService.insertTo(student);
        return "redirect:/all";
    }

    @RequestMapping("/update")
    public String update(HttpServletRequest request) throws ParseException {
        Student student=new Student();
        Integer id=Integer.parseInt(request.getParameter("id"));
        student.setId(id);
        student.setSname(request.getParameter("name"));
        student.setSex(request.getParameter("sex"));
        student.setBirthday(sf.parse(request.getParameter("birthday")));
        student.setHobbies(request.getParameter("hobbies"));
        System.out.println(student);
        studentService.updateTo(student);
        return "redirect:/all";
    }

    @RequestMapping("/upd/{id}")
    public String update(@PathVariable("id")int id, Model model){
        System.out.println(id);
        Student student=studentService.findById(id);
        model.addAttribute("student",student);
        return "updateStudent";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id")int id){
        studentService.deleteTo(id);
        return "redirect:/all";
    }

    @RequestMapping("/queryStu")
    @ResponseBody
    public String query(String sname){
        List<Student> students=studentService.likeStudent(sname);
        String list= JSON.toJSONString(students);
        return list;
    }
}
  • resources下static静态资源
bootstrap官网下载,jquery官方下载

  •  studentList.html
<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <title>studentList</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>学生管理页面</title>
    <link th:href="@{/css/bootstrap.css}" rel="stylesheet">
    <script th:src="@{https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js}"></script>
</head>
<body>
<div style="margin-left:10px;margin-top:10px;">
    <div class="panel panel-primary">
        <div>
            <h3 type="text-align:center">学生管理平台</h3>
        </div>
        <div class="panel-body">
            <div style="display:inline-block;">
<!--                <form method="post" action="/queryStu">-->
                <div style="float:left;padding:6px;">
                    <span>姓名:</span>
                </div>
                <div style="float:left;">
                    <input id="stuName" name="sname" class="form-control" style="width:200px;" type="text" th:placeholder="姓名">
                </div>
                <div style="float:left;margin-left:20px;">
                    <input value="查 询" type="submit" class="btn btn-primary" id="searchbutton">
                </div>
                    <div style="float:right;margin-left:300px;">
                        <a id="add" class="btn btn-primary" th:href="@{/add}">添加</a>
                    </div>
<!--                </form>-->
            </div>
        </div>
    </div>
<table class="table table-striped">
    <thead>
    <tr>
        <th scope="col">#</th>
        <th scope="col">姓名</th>
        <th scope="col">性别</th>
        <th scope="col">生日</th>
        <th scope="col">爱好</th>
        <th scope="col">操作</th>
    </tr>
    </thead>
    <tbody id="tbo">
    <tr th:each="stu:${students}">
        <td scope="row" th:text="${stu.getId()}"></td>
        <td th:text="${stu.getSname()}"></td>
        <td th:text="${stu.getSex()}"></td>
        <td th:text="${#dates.format(stu.getBirthday(),'yyyy-MM-dd')}"></td>
        <td th:text="${stu.getHobbies()}"></td>
        <td>
            <a class="btn btn-primary" th:href="@{/upd/}+${stu.getId()}">编辑</a>
            <a class="btn btn-warning" th:href="@{/delete/}+${stu.getId()}" >删除</a>
        </td>
    </tr>
    </tbody>
</table>
</div>
</body>
<script type="text/javascript">
    //转换日期格式
    function add0(m){return m<10?'0'+m:m };
    function format(shijianchuo)
    {
//shijianchuo是整数,否则要parseInt转换
        var time = new Date(shijianchuo);
        var y = time.getFullYear();
        var m = time.getMonth()+1;
        var d = time.getDate();
        var h = time.getHours();
        var mm = time.getMinutes();
        var s = time.getSeconds();
        return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
    };
    $("#searchbutton").click(function () {
        let name=$("#stuName").val();
        $.ajax({
            url:"/queryStu",
            method:"post",
            data:{sname:name},
            dataType:"json",
            success:function (result) {
                //清空id=data的表格第一行(表头)以外的数据
                $("#tbo").empty();
                console.log(result);
                $.each(result,function (index,stu) {
                    $("#tbo").append(
                        "<tr>"+
                        "<td>"+stu.id +"</td>"+
                        "<td>"+stu.sname +"</td>"+
                        "<td>"+stu.sex+"</td>"+
                        "<td>"+format(stu.birthday)+"</td>"+
                        "<td>"+stu.hobbies+"</td>"+
                        "<td>"+
                        "<a class='btn btn-primary disabled' th:href=\"@{/upd/}+${"+stu.id+"}\">编辑</a>"+
                            "\t&nbsp;"+
                        "<a class='btn btn-warning disabled' th:href=\"@{/delete/}+${"+stu.id+"}\">删除</a>"+
                        "</td>"+
                        "</tr>"
                    )
                })
            },
            fail:function () {
                console.log("no submit");
            }
        })
    })
</script>
</html>
  • index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<style>
    a{
        text-decoration: none;
        color: black;
        font-size: 18px;
    }
    h3{
        width: 180px;
        height: 30px;
        margin: 100px auto;
        text-align: center;
        line-height: 30px;
        background-color: aqua;
        border-radius: 5px;
    }
</style>
</head>
<body>
<h3><a th:href="@{/all}">进入学生管理页面</a> </h3>
</body>
</html>
  • addStudent.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加页面</title>
</head>
<body>
<div style="margin-left:10px;margin-top:100px;">
    <form th:action="@{/insertTo}" method="post">
        <div class="form-group row">
            <label for="inputLastName3" class="col-sm-2 col-form-label">姓名</label>
            <div class="col-sm-10">
                <input type="LastName" name="name" class="form-control" id="inputLastName3" placeholder="LastName">
            </div>
        </div>

        <fieldset class="form-group">
            <div class="row">
                <legend class="col-form-label col-sm-2 pt-0">性别</legend>
                <div class="col-sm-10">
                    <div class="form-check">
                        <input class="form-check-input"  type="radio" name="sex" id="gridRadios1" value="男" checked>
                        <label class="form-check-label" for="gridRadios1">
                            男
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="sex" id="gridRadios2" value="女">
                        <label class="form-check-label" for="gridRadios2">
                            女
                        </label>
                    </div>
                    <div class="form-check disabled">
                        <input class="form-check-input" type="radio" name="gender" id="gridRadios3" value="option3" disabled>
                        <label class="form-check-label" for="gridRadios3">
                            无
                        </label>
                    </div>
                </div>
            </div>
        </fieldset>
        <div class="form-group row">
            <label for="inputBirth3" class="col-sm-2 col-form-label">生日</label>
            <div class="col-sm-10">
                <input type="Birth" name="birthday" class="form-control" id="inputBirth3" placeholder="yyyy-MM-dd">
            </div>
        </div>
        <div class="form-group row">
            <label for="inputBirth1" class="col-sm-2 col-form-label">爱好</label>
            <div class="col-sm-10">
                <textarea type="Hobbies" name="hobbies" class="form-control" id="inputBirth1"></textarea>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-sm-10">
                <button type="submit" class="btn btn-primary">添加</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>
  • updateStudent.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改页面</title>
</head>
<body>
<div style="margin-left:10px;margin-top:100px;">
    <form th:action="@{/update}" method="get">
        <input hidden th:value="${student.getId()}" name="id"/>
        <div class="form-group row">
            <label for="inputLastName3" class="col-sm-2 col-form-label">姓名</label>
            <div class="col-sm-10">
                <input type="LastName" name="name" class="form-control" id="inputLastName3" th:placeholder="${student.getSname()}">
            </div>
        </div>

        <fieldset class="form-group">
            <div class="row">
                <legend class="col-form-label col-sm-2 pt-0">性别</legend>
                <div class="col-sm-10">
                    <div class="form-check">
                        <input class="form-check-input"  type="radio" name="sex" id="gridRadios1" checked value="男">
                        <label class="form-check-label" for="gridRadios1">
                            男
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="sex" id="gridRadios2" value="女">
                        <label class="form-check-label" for="gridRadios2">
                            女
                        </label>
                    </div>
                    <div class="form-check disabled">
                        <input class="form-check-input" type="radio" name="sex" id="gridRadios3" value="option3" disabled>
                        <label class="form-check-label" for="gridRadios3">
                            无
                        </label>
                    </div>
                </div>
            </div>
        </fieldset>
        <div class="form-group row">
            <label for="inputBirth3" class="col-sm-2 col-form-label">生日</label>
            <div class="col-sm-10">
                <input type="btith" name="birthday" class="form-control" id="inputBirth3" th:placeholder="${#dates.format(student.getBirthday(),'yyyy-MM-dd')}">
            </div>
        </div>
        <div class="form-group row">
            <label for="inputBirth1" class="col-sm-2 col-form-label">爱好</label>
            <div class="col-sm-10">
                <textarea type="Hobbies" name="hobbies" class="form-control" id="inputBirth1" th:text="${student.getHobbies()}"></textarea>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-sm-10">
                <button type="submit" class="btn btn-primary">修改</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>
  • 自我总结

  • ajax使用还不行,ajax通过json传参等

  • jquery不熟悉

  • 爱好没有使用选择框等等

  • 页面需要花时间学习

  • 效果

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我愿为一粒沙

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值