springboot入门学习案例

本文介绍了如何使用SpringBoot结合JPA和JSP实现简单的CRUD操作。首先,创建Maven工程并引入SpringBoot相关依赖,接着定义Student实体类和StudentRepository接口,实现数据的查询、删除、修改和添加。然后,通过StudentRepositoryImpl完成具体的数据操作。接下来,创建StudentHander控制器,采用RESTful风格处理HTTP请求。最后,配置application.yml,启动SpringBoot应用,并整合JSP,实现页面展示和交互。此外,还展示了index.jsp和save.jsp两个JSP页面的代码,用于展示学生信息和数据的添加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springBoot

1.创建Maven工程,导入相关依赖

<!--继承父包-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
    </parent>

    <dependencies>
        <!--web启动jar包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
      <!--配置lombok-->
      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.16</version>
      </dependency>

        
    </dependencies>

2.创建Student实体类


package com.xing;

import lombok.Data;

@Data
public class Student {
    private Long id;
    private String name;
    private int age;
}

3.StudentRepository

3.1 Restful风格

删除 delete
查询 get
修改 put
增加 post

3.2 接口实现类

package com.xing.repository;

import com.xing.entity.Student;

import java.util.Collection;

public interface StudentRepository {

    public Collection<Student> findAll();    //查询所有,不只一个,要用集合承接
    public Student findById(long id);  //查询一个,只需要用Student接就好啦
    public void saveOrUpdate(Student student); //保存或者更新,不只有一个参数,要用对象封装起来,不需要返回值
    public void deleteById(long id); //根据id删除,不需要返回值
}

4.StudentRepositoryImPl

package com.xing.repository.impl;

import com.xing.entity.Student;
import com.xing.repository.StudentRepository;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Repository
public class StudentRepositoryImpl implements StudentRepository {

    private static Map<Long,Student> studentMap; //定义静态的map集合

    static {
        studentMap=new HashMap<>();
        studentMap.put(1l,new Student(1l,"邢福豪",22));
        studentMap.put(2l,new Student(2l,"张三",23));
        studentMap.put(3l,new Student(3l,"李四",24));
    }

    @Override
    public Collection<Student> findAll() {
        return studentMap.values();
    }

    @Override
    public Student findById(long id) {
        return studentMap.get(id);
    }

    @Override
    public void saveOrUpdate(Student student) {
        studentMap.put(student.getId(),student);
    }

    @Override
    public void deleteById(long id) {
        studentMap.remove(id);
    }
}

5.StudentHander

package com.xing.controller;

import com.xing.entity.Student;
import com.xing.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@RestController
@RequestMapping("/student")
public class StudentHander {

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/findAll")      //Rest风格,查询用get
    public Collection<Student> findAll(){
        return  studentRepository.findAll();
    }

    @GetMapping("/findById/{id}") //Rest风格,查询用get
    public Student findById(@PathVariable("id") long id){
        return studentRepository.findById(id);
    }

    @PostMapping("/save")    //Rest风格,新增用post,响应的是json格式,要用@RequestBody展示
    public void save(@RequestBody Student student){
         studentRepository.saveOrUpdate(student);
    }

    @PutMapping("/update")   //Rest风格,修改用put,响应的是json格式,要用@RequestBody展示
    public void update(@RequestBody Student student){
        studentRepository.saveOrUpdate(student);
    }

    @DeleteMapping("/deleteById/{id}")  //Rest风格,删除用delete
    public void deleteById(@PathVariable("id") long id){
        studentRepository.deleteById(id);
    }

}

6.application.yml

server:
  port: 9090

7.启动类

必须在其他包之上,是父级节点

package com.xing;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

@springBootApplication 表示当前类是Spring Boot的入口,Application类的存放位置,必须是其他相关业务类存放位置的父级位置

SpringBoot 整合JSP

1.pom.xml

<parent>
  <groupId>org.springframework.boot</groupId>
  <version>2.3.3.RELEASE</version>
  <artifactId>spring-boot-starter-parent</artifactId>
</parent>

<dependencies>

  <!--web-->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <!--整合 JSP-->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
  </dependency>
  <dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <version>9.0.43</version>
  </dependency>

  <!--JSTL 标准标签库-->
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>

</dependencies>

2.创建application.yml

server:
  port: 8181
spring:
  mvc:
    view:
      prefix: /
      suffix: .jsp

3.创建Handler

3.1.Controller区别

@RestController //返回的是数据
@Controller //返回的是模型和视图

3.2.Handler实现

package com.xing.controller;

import com.xing.entity.Student;
import com.xing.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


@Controller //返回的是模型和视图
@RequestMapping("/hello")
public class HelloHandler {

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("list",studentRepository.findAll());
        return modelAndView;
    }

    @GetMapping("/deleteById/{id}") //因为超链接是get传递的,所以现在暂时不能用rest请求
    public String deleteById(@PathVariable("id")long id){
        studentRepository.deleteById(id);
        return "redirect:/hello/index";
    }

    @PostMapping("/save")
    public String save(Student student){
        studentRepository.saveOrUpdate(student);
        return "redirect:/hello/index";
    }

    @PostMapping("/update")
    public String update(Student student){
        studentRepository.saveOrUpdate(student);
        return "redirect:/hello/index";
    }

    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable("id") long id){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("student",studentRepository.findById(id));
        modelAndView.setViewName("update");
        return modelAndView;
    }

}

4.index.jsp

<%--
  Created by IntelliJ IDEA.
  User: xingfuhao
  Date: 2021/4/6
  Time: 13:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false"%>
<html>
<head>
    <title>学生信息</title>
</head>
<body>
    <h1>学生信息</h1>
    <table>
        <tr>
            <td>学生编号</td>
            <td>学生姓名</td>
            <td>学生年龄</td>
            <td>操作</td>
        </tr>
        <c:forEach items="${list}" var="student">
            <tr>
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>${student.age}</td>
                <td>
                    <a href="/hello/findById/${student.id}">修改</a>
                    <a href="/hello/deleteById/${student.id}">删除</a>
                </td>

            </tr>
        </c:forEach>
    </table>
<a href="/save.jsp">添加学生</a>
</body>
</html>

添加

<%--
  Created by IntelliJ IDEA.
  User: xingfuhao
  Date: 2021/4/6
  Time: 13:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <form method="post" action="/hello/save">
        ID:<input type="text" name="id" /><br/>
        姓名:<input type="text" name="name"/><br/>
        年龄:<input type="text" name="age"/><br/>
        <input type="submit" value="提交">
    </form>

</body>
</html>

修改

<%--
  Created by IntelliJ IDEA.
  User: xingfuhao
  Date: 2021/4/6
  Time: 13:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <form method="post" action="/hello/update">
        ID:<input type="text" name="id" value="${student.id}" readonly/><br/>
        姓名:<input type="text" name="name" value="${student.name}" /><br/>
        年龄:<input type="text" name="age" value="${student.age}"/><br/>
        <input type="submit" value="提交">
    </form>

</body>
</html>

参考b站视频,做的学习笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值