一:前言

这个就是用springboot实现后台管理(CRUD)的小demo,相比于SSM的配置地狱,springboot的自动配置确实很牛,tomcat都内置,我们想要修改相关的信息只要在yaml配置文件修改就行了,关于Dao层,这个mybatis-plus,quo实是很牛逼,这个连sql都是省略了,但也仅限于单表的sql,复杂的sql语句还得靠mapper.xml中进行书写。总之一句话,你不学SSM,springboot里面很多原理不理解,但是学了springboot,SSM配置起来是真麻烦。

二:用到的相关技术

spingboot(2.6.3)+Mybatis-Plus+Maven+thmeleaf+Mysql
环境是JDK1.8,maven是3.4.1,mysql5.7

三:实现功能流程

  • 在springboot官方文档中找到对应的 场景启动器(starter)
  • 分析其–xxxautoConfigration
  • 然后找到xxxxProperties绑定了配置文件有哪些。
  • 哪些需要修改 还是自定义

四:功能展示

1:登录首页

在这里插入图片描述

2:主页面

在这里插入图片描述

3:展示表单(select)

在这里插入图片描述

4:删除一条记录(delete)

点击删除 会自动删除,同时的话,在那页删除还会自动回到那页,这里就是点击删除 发送这个请求的时候,把当前页的信息也给发送处理的请求的,所以请求里信息会被Controller层处理,处理完请求在把该页信息用到反应请求的路径上。
在这里插入图片描述

5:修改一条记录(Update)

在这里插入图片描述
修改页面:
在这里插入图片描述

6:增加一条记录信息(insert)

在这里插入图片描述
在这里插入图片描述

五:上码

1:导入相关场景启动器

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wyj</groupId>
    <artifactId>springboot-05-web02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-05-web02</name>
    <description>springboot-05-web02</description>
    <properties>
        <java.version>11</java.version>
        <repackage.classifier/>
        <spring-native.version>0.11.2</spring-native.version>
        <kotlin.version>1.6.20-M1</kotlin.version>
    </properties>
    <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>
        <!--导入jdbc的场景启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <!--导入数据库的驱动包  因为我们不知道到底是哪个驱动器  mysql 还是其他的 -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--导入Mybatis-Plus的场景-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>



        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-test</artifactId>
            <version>${kotlin.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                    <classifier>${repackage.classifier}</classifier>
                    <image>
                        <builder>paketobuildpacks/builder:tiny</builder>
                        <env>
                            <BP_NATIVE_IMAGE>true</BP_NATIVE_IMAGE>
                        </env>
                    </image>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.experimental</groupId>
                <artifactId>spring-aot-maven-plugin</artifactId>
                <version>${spring-native.version}</version>
                <executions>
                    <execution>
                        <id>test-generate</id>
                        <goals>
                            <goal>test-generate</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>generate</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jvmTarget>1.8</jvmTarget>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>testCompile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/release</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/release</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <profiles>
        <profile>
            <id>native</id>
            <properties>
                <repackage.classifier>exec</repackage.classifier>
                <native-buildtools.version>0.9.9</native-buildtools.version>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-launcher</artifactId>
                    <scope>test</scope>
                </dependency>
            </dependencies>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.graalvm.buildtools</groupId>
                        <artifactId>native-maven-plugin</artifactId>
                        <version>${native-buildtools.version}</version>
                        <extensions>true</extensions>
                        <executions>
                            <execution>
                                <id>test-native</id>
                                <phase>test</phase>
                                <goals>
                                    <goal>test</goal>
                                </goals>
                            </execution>
                            <execution>
                                <id>build-native</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>build</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>

2:yaml配置文件

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/smbms?useSSL=true
    username: root
    password: wyj
    driver-class-name: com.mysql.jdbc.Driver


#Mybatis-plus配置
mybatis-plus:
  #全局配置文件的路径
  config-location: classpath:mybatis/mybatis-config.xml
  #指明.xml文件的路径
  mapper-locations: classpath:mybatis/mapper/*.xml

3:Pojo

(1):admin

package com.wyj.Pojo;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Admin {
    private String userName;
    private String passWord;
}

(2):User

package com.wyj.Pojo;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "userTO")
public class User {
    //Mybatis-Plus的测试数据
    private Integer id;
    private String name;
    private Integer age;
    private String email;

}

4:mapper

这里继承了BaseMapper,很多sql就不用写了,这里还需要注意 的是,默认的表明是和类名一致的,如过类名和表名不一致的话,需要用注解@TableName 把表名注上

package com.wyj.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wyj.Pojo.User;
import org.apache.ibatis.annotations.Mapper;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper extends BaseMapper<User> {

}

5:Service层

(1)Service接口

package com.wyj.Service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyj.Pojo.User;
import com.wyj.mapper.UserMapper;

import java.util.List;

public interface UserService extends IService<User>  {



}

(2):Service的实现类

package com.wyj.Service.imp;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyj.Pojo.User;
import com.wyj.Service.UserService;
import com.wyj.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImp extends ServiceImpl<UserMapper,User> implements UserService {

}

6:Controller层

(1):IndexController

package com.wyj.Controller;

import com.wyj.Pojo.Admin;
import com.wyj.Pojo.TextUser;
import com.wyj.Pojo.User;
import com.wyj.Service.imp.TextUserServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    //设置首页 只要请求是'/'或者是'/login'  我们就会返回首页
    @RequestMapping(value = {"/","/login"})
    public String loginPage() {
        return "login";
    }

    @RequestMapping("/let")
    public String loginPage(Admin admin, HttpSession session, Model model) {

        if ("wyj".equals(admin.getUserName()) && "123".equals(admin.getPassWord())) {
            session.setAttribute("loginUser",admin);
            return "redirect:main.html";//这里重定向的是一个请求所以得重新写一个
        }else{                            //一般我们return的是一个  html 页面
                                                //视图解析器自动给我们加上前缀和后缀
            model.addAttribute("msg","请输入正确的密码和用户名");
            return "login";
        }
    }
    @RequestMapping("/main.html")
    public String showPage() {
        return "main";
    }


}

(2):TableController

package com.wyj.Controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyj.Pojo.User;
import com.wyj.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class TableController {

    @Autowired
    private UserService userService;

    @GetMapping("/basic_table")
    public String basic_table() {
        return "table/basic_table";
    }

    @GetMapping("/dynamic_table")
    public String dynamic_table(@RequestParam(value = "pn",defaultValue = "1") Integer pn, Model model) {
        //List<User> list = userService.getUserList();

        //构造分页参数
        Page<User> page = new Page<>(pn, 2);
        //调用page进行分页
        Page<User> userPage = userService.page(page, null);
        long current = userPage.getCurrent();//当前是几页
        long pages = userPage.getPages();//当前总共的页数
        long total = userPage.getTotal();//总共的记录数目/条数

        //获取表当中的数据
        List<User> records = userPage.getRecords();

        //这个userPage里面有我们存着的当前页和我们的表中的数据(但这个数据得靠我们自己取出来)
        model.addAttribute("users",userPage);

        return "table/dynamic_table";
    }

    //删除功能

//    @ResponseBody
    @GetMapping("/delete")
    public String deleteTable(@RequestParam("id") Integer id,
                              @RequestParam(value = "pn",defaultValue = "1") Integer pn,
                              RedirectAttributes ra
                              ) {
        userService.removeById(id);

        //这个相当于从前端获取到一个参数  然后就将其加到我们新的重定向的路径上
        ra.addAttribute("pn",pn);

        return "redirect:dynamic_table";
    }

    //修改一个用户的信息
    @GetMapping("/update")
    public String updateTable(@RequestParam("id") Integer id,
                              @RequestParam("name") String name,
                              @RequestParam("age") Integer age,
                              @RequestParam("email") String email,
                              Model model
                                ) {
        User user = new User();

        //获取到我们要修改用户的信息的id信息
        user.setId(id);

        if(name != null) user.setName(name);
        if(age != null) user.setAge(age);
        if(email != null) user.setEmail(email);
        userService.updateById(user);

        model.addAttribute("msg","修改用户信息成功");

        return "redirect:dynamic_table";
    }

    //增加一个用户
    @GetMapping("/add_table")
    public String addTable(@RequestParam("id") Integer id,
                           @RequestParam("name") String name,
                           @RequestParam("age") Integer age,
                           @RequestParam("email") String email) {

        User user = new User(id, name, age, email);
        userService.save(user);
        return "redirect:dynamic_table";
    }

    @GetMapping("/editable_table")
    public String editable_table() {
        return "table/editable_table";
    }

    @GetMapping("/responsive_table")
    public String responsive_table() {
        return "table/responsive_table";
    }

    @GetMapping("/update_table.html")
    public String getUpdateTable (Model model,Integer id) {

        User user = userService.getById(id);
        model.addAttribute("user",user);

        return "table/update_table";
    }

    //转发到增加用户页面
    @GetMapping("add_table.html")
    public String addTable() {

        return "table/add_table";
    }

}

7:拦截器

package com.wyj.MyLanJie;


import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class loginInterceptor implements HandlerInterceptor {

    /**
     *
     * 方法处理前:如果返回true 那么就继续往下执行 返回false就不往下执行了
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    /**
     * preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用,SpringMVC中的Interceptor拦截器是链式的,可以同时存在
     * 多个Interceptor,然后SpringMVC会根据声明的前后顺序一个接一个的执行,而且所有的Interceptor中的preHandle方法都会在
     * Controller方法调用之前调用。SpringMVC的这种Interceptor链式结构也是可以进行中断的,这种中断方式是令preHandle的返
     * 回值为false,当preHandle的返回值为false的时候整个请求就结束了。
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        Object loginUser = session.getAttribute("loginUser");
        if(loginUser != null) {
            return true;//放行
        }
        request.setAttribute("msg","请先登录");
        request.getRequestDispatcher("/login").forward(request,response);

        return false;
    }

    @Override//方法执行后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

这个需要我们自动配置一下,有些页面是放行的有些页面是拦截的

package com.wyj.Config;

import com.wyj.MyLanJie.loginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class interceptorConfig implements WebMvcConfigurer {


    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new loginInterceptor())//将拦截器注册到容器中
                         .addPathPatterns("/**")//设置拦截要求
                        .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**",
                "/js/**","/aa/**","/let");//放行的要求
    }

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐