拾光分享网 | 一个有趣的IT资源分享网

SpringBoot框架学习记录,学习笔记第一篇

一. 搭建Spring Boot程序

  1. 使用IDEA创建Spring Boot项目,参考网站:https://blog.csdn.net/stronglyh/article/details/80685187
  2. 使用官网网址搭建:https://start.spring.io/

项目成功后pom.xml截图
2020-03-04_211212.jpg

二. 初学Hello Word实现

2.1. 项目实现

@RestController
public class day01Controller {
 
    @RequestMapping("/hello")
    public String HelloWord(){
        return "您好,Spring Boot";
    }
    
}
 
@SpringBootApplication
@ServletComponentScan
public class App {
 
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
 
}

2.1. 遇见的错误

2020-03-04_211129.jpg

解决方法

  1. Application启动类的位置不对:要将Application类放在最外侧,即包含所有子包
    ,spring-boot会自动加载启动类所在包下及其子包下的所有组件。
  2. springboot的配置文件有误:关于application.yml或application.properties文件中视图解析器的配置问题。在pom文件下的spring-boot-starter-paren版本较高时使用以下配置
  3. 控制器的url访问路径与注解@GetMapping("/xxxx")不匹配
  4. 使用@RestController

三. Spring Boot数据库操作,学生信息增删改

3.1. application.yml配置

#配置端口
server:
  port: 80
  context-path: /
  tomcat:
    uri-encoding: UTF-8
# 数据源配置
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/hispringboot?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
#数据库操作
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  thymeleaf:
    cache: false
#配置日志文件
logging:
  level:
    root: info
    com.lrm: debug
  file: log/blog-dev.log

3.2. 程序预览实现

2020-03-04_211520.jpg

2020-03-04_211600.jpg

3.3. 项目代码实现

3.3.1. Controller实现

package top.hiai.controller;
 
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
 
import top.hiai.entity.Student;
import top.hiai.service.StudentService;
 
/**
* @Author www.hiai.top
* @Email  goodsking@163.com
* @Message 更多资源尽在www.hiai.top,开发者:黄康权
* @Introduction 类的介绍
*/
 
@Controller
@RequestMapping(value = "/student")
public class StudentController {
    @Resource
    private StudentService studentService = new  StudentService();
    
    /**
     * 遍历所有的学生列表
     * @return
     */
    @RequestMapping("/list")
    public ModelAndView studentList(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("studentList",studentService.list());
        mav.addObject("title", "学生列表");
        mav.setViewName("studentList");
        return mav;
    }
    /**
     * 显示添加学生的视图
     * @return
     */
    @RequestMapping("/addview")
    public ModelAndView studentAddView(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("title", "添加学生");
        mav.setViewName("studentAdd");
        return mav;
    }
    /**
     * 添加学生信息
     * @param student
     * @return
     * 指定提交get和post方式
     * 1.@RequestMapping(value="/add",method=RequestMethod.POST)
     * 2.@PostMapping(value="/add")
     */
    @RequestMapping(value="/add",method=RequestMethod.POST)
    public String studentAdd(Student student){
        studentService.studentAdd(student);
        return "redirect:/student/list";            //重定向
    }
    
    /**
     * 根据学生ID查找学生信息,修改学生信息
     * @param id
     * @return
     */
    @RequestMapping("/stuedit/{id}")
    public ModelAndView studentUpload(@PathVariable("id")Integer id){
        ModelAndView mav = new ModelAndView();
        //通过ID查找信息
        mav.addObject("student",studentService.findOne(id));
        mav.addObject("title", "修改学生信息");
        mav.setViewName("studentEdit");
        return mav;
    }
    
    /**
     * 修改学生信息
     * @param student
     * @return
     */
    @PostMapping(value="/upload")
    public String studentUpload(Student student){
        studentService.studentAdd(student);
        return "redirect:/student/list";            //重定向
    }
    
    /**
     * 删除学生信息
     * @param id
     * @return
     * @RequestMapping("/studel")  中的value可以省略
     */
    @GetMapping("/studel/{id}")
    public String studentDelete(@PathVariable("id")Integer id){
        studentService.stuDelete(id);
        
        //return "forward:/student/list";            //Spring Boot 转发
        //return studentList;                        //重定向
        //return "forward:/studentList.html";        //这三种都失败了
        
        return "redirect:/student/list";            //重定向
    }
    /**
     * 遍历学生信息,返回json数据
     * @return
     */
    //@ResponseBody的作用其实是将java对象转为json格式的数据。
    @ResponseBody
    @RequestMapping("/stujson/{id}")
    public Map<String,Object> studentJson(@PathVariable("id")Integer id){
//        Student student = new Student();
        Map<String,Object> resultMap = new HashMap<>();
        //返回所有学生的新
//        List<Student> studentLists = studentService.list();
        
        //根据学生ID查找学生信息 
        Student studentLists = studentService.findOne(id);
        resultMap.put("code", 0);
        resultMap.put("data", studentLists);
        return resultMap;
    }
}

3.3.2. Entity实现

package top.hiai.entity;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
 
/**
* @Author www.hiai.top
* @Email  goodsking@163.com
* @Message 更多资源尽在www.hiai.top,开发者:黄康权
* @Introduction 类的介绍
*/
 
@Entity
@Table(name="t_student")
public class Student{
    
    /**
     * 
     */
    //private static final long serialVersionUID = 1L;
 
    @Id
    @GeneratedValue
    private Integer id;
    
    private String username;
    
    private String sex;
    
    private Integer age;
    
    
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
 
}

3.3.3. Repository实现

package top.hiai.repository;
 
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
 
import top.hiai.entity.Student;
 
/**
* @Author www.hiai.top
* @Email  goodsking@163.com
* @Message 更多资源尽在www.hiai.top,开发者:黄康权
* @Introduction 类的介绍
*/
 
public interface StudentRepository extends JpaRepository<Student, Integer>,JpaSpecificationExecutor<Student> {
}

3.3.4. Service 实现

package top.hiai.service;
 
import java.util.List;
 
import javax.annotation.Resource;
 
import org.springframework.stereotype.Service;
 
import top.hiai.entity.Student;
import top.hiai.repository.StudentRepository;
 
/**
* @Author www.hiai.top
* @Email  goodsking@163.com
* @Message 更多资源尽在www.hiai.top,开发者:黄康权
* @Introduction 类的介绍
*/
 
@Service("studentService")
public class StudentService {
    
    @Resource
    private StudentRepository studentRepository;
    
    /**
     * 遍历所有的学生
     * @return
     */
    public List<Student> list(){
        return studentRepository.findAll();
    }
    
    /**
     * 添加学生信息
     * @param student
     * @return
     * 没有ID主键就是添加
     * 有ID主键就是修改
     */
    public void studentAdd(Student student){
        studentRepository.save(student);
    }
    
    /**
     * 根据ID查找信息
     * @param id
     * @return
     */
    
    public Student findOne(int id){
        return studentRepository.findOne(id);
    }
    /**
     * 删除学生信息
     * @param id
     */
    public void stuDelete(int id){
        studentRepository.delete(id);
    }
 
}

3.3.5. HTML代码实现

首页HTML
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title th:text="${title}+'-拾光博客'"></title>
</head>
<body>
    <p><a href="/student/addview">添加学生</a></p>
    <table>
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>年龄</th>
            <th>操作</th>
        </tr>
        <tr th:each="student:${studentList}">
            <td th:text="${student.id}"></td>
            <td th:text="${student.username}"></td>
            <td th:text="${student.sex}"></td>
            <td th:text="${student.age}"></td>
            <td>
                <!-- <a href="/student/studel/?id=" th:value="${student.id}">删除</a> -->
                <a th:href="@{'/student/stuedit/'+${student.id}}">修改</a>
                <a th:href="@{'/student/studel/'+${student.id}}">删除</a>
            </td>
        </tr>
    </table>
</body>
</html>
 
修改HTML代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title th:text="${title}+'-拾光博客'"></title>
</head>
<body>
    <form action="/student/upload" method="post">
        <input type="hidden" name="id"  th:value="${student.id}"/>
        学生姓名:<input type="text" name="username" th:value="${student.username}"/><br/>
        学生性别:<input type="text" name="sex" th:value="${student.sex}"/><br/>
        学生年龄:<input type="text" name="age" th:value="${student.age}"/><br/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

3.3.6. pom.xml

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <groupId>top.hiai</groupId>
    <artifactId>HiSpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>HiSpringBoot</name>
    <description>Demo project for Spring Boot</description>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
    
    <!-- 使用阿里 maven 库 -->
    <repositories>
        <repository>
            <id>ali-maven</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
                <checksumPolicy>fail</checksumPolicy>
            </snapshots>
        </repository>
    </repositories>
 
    <dependencies>
    
            <!-- 自动加载工具,每次保存自动加载 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        
        <!-- Spring Boot web核心-->
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        
        <!-- Mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
          <!-- 错误日志处理 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
       
        <!-- 数据库操作Jap -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        
        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>
欢迎您的转载:拾光分享网 | 一个有趣的IT资源分享网 » SpringBoot框架学习记录,学习笔记第一篇


评论 1

  • 昵称*
  • 邮箱 (必填)
  • 网址
  1. # 1
    frank的头像

    哈哈

    frank (2020-03-04) 回复