3、springboot项目案例小结

springboot项目案例小结

一、创建项目

使用idea工具,创建springboot项目,引入相关依赖

(lombok   spring web  Thymeleaf   mybatis framework  mysql Driver   Devtools)

二、添加依赖

引入项目所需依赖,如pagehelper、swagger2(按需求来引入)

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.13</version>
</dependency>

<!-- 引入swagger-ui包  -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- 引入swagger包  -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.0.0</version>
</dependency>

三、设置配置文件(端口号、数据源、热部署、thymeleaf模板)

spring:
  devtools:
    restart:
      enabled: true
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/myschool?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: root

#thymeleaģ
  thymeleaf:
    mode: HTML5
    encoding: UTF-8
    cache: false
    suffix: .html



mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: zy.train.entity

#pagehelper
pagehelper:
  helperDialect: mysql
  rowBoundsWithCount: true
  pageSizeZero: true
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
  returnPageInfo: check

AdminMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="zy.train.mapper.AdminMapper" >
  <resultMap id="AdminResultMap" type="Admin" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="user" property="user" jdbcType="VARCHAR" />
    <result column="pass" property="pass" jdbcType="VARCHAR" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="SMALLINT" />
    <result column="headPhoto" property="headphoto" jdbcType="VARCHAR" />
    <result column="creatTime" property="creattime" jdbcType="TIMESTAMP" />
    <result column="remarks" property="remarks" jdbcType="VARCHAR" />
  </resultMap>

  <sql id="sf-admin">
    <where>
      <if test="id != null and id != 0">and id = #{id}</if>
      <if test="user != null and user != ''">and user = #{user}</if>
      <if test="sex != null and sex != ''">and sex = #{sex}</if>
    </where>
  </sql>

  <insert id="insert" parameterType="Admin" >
    insert into admin
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="user != null" >
        user,
      </if>
      <if test="pass != null" >
        pass,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="sex != null" >
        sex,
      </if>
      <if test="age != null" >
        age,
      </if>
      <if test="headphoto != null" >
        headPhoto,
      </if>
      <if test="creattime != null" >
        creatTime,
      </if>
      <if test="remarks != null" >
        remarks,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="user != null" >
        #{user,jdbcType=VARCHAR},
      </if>
      <if test="pass != null" >
        #{pass,jdbcType=VARCHAR},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=SMALLINT},
      </if>
      <if test="headphoto != null" >
        #{headphoto,jdbcType=VARCHAR},
      </if>
      <if test="creattime != null" >
        #{creattime,jdbcType=TIMESTAMP},
      </if>
      <if test="remarks != null" >
        #{remarks,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

  <update id="update" parameterType="Admin" >
    update admin
    <set >
      <if test="user != null" >
        user = #{user,jdbcType=VARCHAR},
      </if>
      <if test="pass != null" >
        pass = #{pass,jdbcType=VARCHAR},
      </if>
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=SMALLINT},
      </if>
      <if test="headphoto != null" >
        headPhoto = #{headphoto,jdbcType=VARCHAR},
      </if>
      <if test="creattime != null" >
        creatTime = #{creattime,jdbcType=TIMESTAMP},
      </if>
      <if test="remarks != null" >
        remarks = #{remarks,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

  <delete id="delete" parameterType="Integer" >
    delete from admin where id = #{id,jdbcType=INTEGER}
  </delete>

  <select id="getOne" resultType="Admin" parameterType="Integer" >
    select  * from admin where id = #{id,jdbcType=INTEGER}
  </select>

  <select id="getList" resultMap="AdminResultMap" parameterType="Admin" >
    select  * from admin <include refid="sf-admin"></include>
  </select>
</mapper>

Swagger2configuration

@Configuration
@EnableSwagger2
public class Swagger2configuration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //扫描端口
                .apis(RequestHandlerSelectors.basePackage("zy.train"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger-bootstrap-ui RESTful APIs")
                .description("员工信息管理")
                .termsOfServiceUrl("http://localhost:8080/")
                .contact("1160285648@mail.com")
                .version("1.0")
                .build();
    }
}

四、项目结构及热部署设置

项目目录结构如下

点击File —> Settings —> Build,Excution —> Complier

使用快捷键ctrl+shift+alt+/点击Registry

五、项目代码

1、编写实体类

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor

public class Admin{
    //实体类属性
    private Integer id;

    private String user;

    private String pass;

    private String name;

    private String sex;

    private Short age;

    private String headphoto;

    private Date creattime;

    private String remarks;
}

2、持久化接口AdminMapper

@Mapper
@Repository
public interface AdminMapper {

    int insert(Admin admin);

    int update(Admin admin);

    int delete(Integer id);

    Admin getOne(Integer id);

    List<Admin> getList(Admin admin);
}

3、服务层接口和实现类

public interface  AdminService {

    int insert(Admin admin);

    int update(Admin admin);

    int delete(Integer id);

    Admin getOne(Integer id);

    List<Admin> getList(Admin admin);

    PageInfo<Admin> PageList(Admin admin, Integer pageNum, Integer pageSize);
}
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public int insert(Admin admin) {
        return adminMapper.insert(admin);
    }

    @Override
    public int update(Admin admin) {
        return adminMapper.update(admin);
    }

    @Override
    public int delete(Integer id) {
        return adminMapper.delete(id);
    }

    @Override
    public Admin getOne(Integer id) {
        return adminMapper.getOne(id);
    }

    @Override
    public List<Admin> getList(Admin admin) {
        return adminMapper.getList(admin);
    }

    @Override
    public PageInfo<Admin> PageList(Admin admin, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize,true);
        return  new PageInfo<>(adminMapper.getList(admin));
    }

}

4、编写控制层

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/list")
    public String test(@RequestParam(value = "pageNum", required = false,defaultValue = "1") Integer pageNum,@RequestParam(value = "pageSize", required = false,defaultValue = "5") Integer pageSize,Admin admin, Model model) {
        model.addAttribute("admin",admin);
        model.addAttribute("pageInfo",adminService.PageList(admin,pageNum,pageSize));
        return "list";
    }

    @RequestMapping("/input")
    public String update(@RequestParam(value = "id", required = false) Integer id,Model model) {
        if(id!=null && id != 0) {
            model.addAttribute("admin", adminService.getOne(id));
        }
        return "input";
    }

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String save(Admin admin) {
        System.out.println(admin);
        if(admin.getId() != null && admin.getId() != 0){
            adminService.update(admin);
        }else{
            admin.setCreattime(new Date());
            adminService.insert(admin);
        }
        return "redirect:list";
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam(value = "id", required = false) Integer id) {
        adminService.delete(id);
        return "redirect:list";
    }
}

六、前端页面

list.html

<!DOCTYPE html>
<html lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        table{
            margin-top:10px;
            width:600px;
        }
        table,tr,th,td{
            border:1px solid #ff0000;
            border-collapse: collapse;

        }
    </style>
</head>
<body>
<form action="/admin/list" method="post">
    <table>
        <tr>
            <th>ID</th>
            <td><input type="text" name="id" th:value="${admin.id}"  size="30" /></td>
            <th>账号</th>
            <td><input type="text" name="user" th:value="${admin.user}"   size="30" /></td>
        </tr>
        <tr>
            <th>性别</th>
            <td><input type="text" name="sex" th:value="${admin.sex}" size="20" /> </td>
            <th colspan="2"><input type="submit" value="查询" /></th>
        </tr>
    </table>
</form>
<a th:href="${'/admin/input'}">添加</a>
<table>
    <tr>
        <th>ID</th>
        <th>账号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>年龄</th>
        <th>创建时间</th>
        <th>备注</th>
        <th>操作</th>
    </tr>
    <tr th:each="admin:${pageInfo.list}">
        <!--/*@thymesVar id="id" type="zy.train.entity.Admin"*/-->
        <td th:text="${admin.id}"></td>
        <td th:text="${admin.user}"></td>
        <td th:text="${admin.name}">
        <td th:text="${admin.sex}"></td>
        <td th:text="${admin.age}"></td>
        <td th:text="${#dates.format(admin.creattime, 'yyyy-MM-dd hh:mm:ss')}"></td>
        <td th:text="${admin.remarks}"></td>
        <td>
            <a th:href="${'/admin/input?id='+admin.id}">编辑</a>
            <a th:href="${'/admin/delete?id='+admin.id}">删除</a>
        </td>
    </tr>
</table>
<table>
    <tr>
        <td>
            <span th:text="数据总量 +${pageInfo.total}+条"></span>&emsp;&emsp;
            <a th:href="${'/admin/list?pageNum=1&pageSize='+pageInfo.pageSize}"> 首页 </a>&emsp;&emsp;
            <a th:href="${'/admin/list?pageNum='+pageInfo.prePage+'&pageSize='+pageInfo.pageSize}"> 上一页 </a>&emsp;&emsp;
            <a th:href="${'/admin/list?pageNum='+pageInfo.nextPage+'&pageSize='+pageInfo.pageSize}"> 下一页 </a>&emsp;&emsp;
            <a th:href="${'/admin/list?pageNum='+pageInfo.pages+'&pageSize='+pageInfo.pageSize}"> 尾页 </a>
        </td>
    </tr>
</table>
<!--导入jquery.js-->
<script type="text/javascript" th:src="@{/webjars/jquery/3.0.0/jquery.js}"></script>
</body>
</html>

input.html

<!DOCTYPE html>
<html lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="save" method="post">
    <input type="hidden" name="id" th:value="${admin?.id}" /><br /><br />
    <!-- 编号:<input type="text" name="id" readonly="readonly" value="${user.id}" /><br /><br /> -->
    账号:<input type="text" name="user" th:value="${admin?.user}" /><br /><br />
    密码:<input type="text" name="pass" th:value="${admin?.pass}" /><br /><br />
    姓名:<input type="text" name="name" th:value="${admin?.name}" /><br /><br />
    性别:<input type="text" name="sex" th:value="${admin?.sex}" /><br /><br />
    年龄:<input type="text" name="age" th:value="${admin?.age}" /><br /><br />
    头像:<input type="file" name="headphoto" /><br /><br />
    备注:<input type="text" name="remarks" th:value="*{admin?.remarks}" /><br /><br />
    <input type="submit" value="提交"/>
    <input type="button" onclick="history.go(-1);" value="返回" />
</form>
</body>
</html>

七、效果图

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的SpringBoot项目案例,该项目实现了一个简单的RESTful API,用于管理学生信息: 1.创建SpringBoot项目 首先,我们需要创建一个SpringBoot项目。可以使用Spring Initializr(https://start.spring.io/)来创建一个基本的SpringBoot项目,也可以使用IDE(如IntelliJ IDEA或Eclipse)来创建。 2.添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependencies> <!-- Spring Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- H2 Database --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> ``` 这些依赖将帮助我们构建一个基本的Web应用程序,并使用JPA和H2数据库。 3.创建实体类 创建一个名为Student的实体类,该类包含id、name和age属性: ```java @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // getters and setters } ``` 4.创建Repository 创建一个名为StudentRepository的接口,该接口继承自JpaRepository,并提供一些自定义方法: ```java @Repository public interface StudentRepository extends JpaRepository<Student, Long> { List<Student> findByName(String name); } ``` 5.创建Controller 创建一个名为StudentController的类,该类包含一些RESTful API: ```java @RestController @RequestMapping("/students") public class StudentController { @Autowired private StudentRepository studentRepository; @GetMapping("") public List<Student> getAllStudents() { return studentRepository.findAll(); } @GetMapping("/{id}") public Student getStudentById(@PathVariable Long id) { return studentRepository.findById(id).orElse(null); } @PostMapping("") public Student createStudent(@RequestBody Student student) { return studentRepository.save(student); } @PutMapping("/{id}") public Student updateStudent(@PathVariable Long id, @RequestBody Student student) { Student existingStudent = studentRepository.findById(id).orElse(null); if (existingStudent != null) { existingStudent.setName(student.getName()); existingStudent.setAge(student.getAge()); return studentRepository.save(existingStudent); } else { return null; } } @DeleteMapping("/{id}") public void deleteStudent(@PathVariable Long id) { studentRepository.deleteById(id); } @GetMapping("/search") public List<Student> searchStudents(@RequestParam String name) { return studentRepository.findByName(name); } } ``` 6.运行应用程序 现在,我们可以运行应用程序并测试RESTful API。可以使用Postman或类似的工具来测试API。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值