主頁 > 前端設計 > 【爆肝推薦】手摸手帶你做后臺管理專案(第二章)登陸和用戶管理

【爆肝推薦】手摸手帶你做后臺管理專案(第二章)登陸和用戶管理

2021-10-04 08:19:38 前端設計

前情提要

上一篇搭建了基礎的架子,這一篇搭建頁面架子,主要偏前端一點, 手摸手上一篇地址,點擊跳轉
這篇不做賬號登陸的驗證,留到下一篇shiro的時候一起做了,寫到最后幾章更像是在寫前后端分離,
頁面的跳轉沒有走controller,因為thymeleaf模版的原因,要不然每個頁面都要寫一個跳轉的,
后面大部分都在前端解決跳轉問題

第二章需要搭建的頁面如下:
在這里插入圖片描述

在這里插入圖片描述

正文開始

新建以下檔案和檔案夾

在這里插入圖片描述

修改application.yml檔案

設定映射路徑為:templates檔案夾下

thymeleaf:
  cache: false
  encoding: utf-8
  mode: HTML5
  prefix: classpath:/templates/
  suffix: .html
  # 保證html能直接訪問,不需要跳轉controller,后期動態管理頁面地址
resources: 
  static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/	

詳細圖片
在這里插入圖片描述

layui-admin.css

.layui-admin-bg{
    background-color: #20222A !important ;
}
.layui-admin-border {
    box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
}
.panel {
    padding: 15px;
}
.panel-height {
    height: 600px;
}
.card-header {
    height: 60px;
}
.title {
    text-align: center;
}
.layui-layer-title {
    background-color: #001529 !important;
    color:#fff !important;
}
.layui-layer-close1 {
    color:#fff !important;
}
.layui-upload-img {
    width: 92px;
    height: 92px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 98px;
    height: 98px;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 98px;
    height: 98px;
    display: block;
}

.el-upload-list--text {
    display: none;
}

.el-dialog {
    margin-top: 20px !important;
}
.el-dialog > .el-dialog__header {
    background-color: #001529 !important;
}
.el-dialog__title {
    color: #fff !important;
}
.el-dialog__body {
    padding-left: 0px !important;
}

login.css代碼

.login-form {
    width: 25%;
    margin: auto;
    margin-top: 120px;
}
.login-title {
    text-align: center;
    font-size: 30px;
}
.input-div,.input-div2{
    display:flex;
    border: 1px solid #eee ;
    background-color: #fff;
    height: 38px;
    line-height: 38px;
    padding: 0px 10px;
}
.layui-input {
    border-style: none;
}

input::-webkit-input-placeholder {
    color: #ccc;
}
input:-moz-placeholder {
    color: #ccc;
}
input::-moz-placeholder {
    color: #ccc;
}
input:-ms-input-placeholder {
    color: #ccc;
}
.layui-form {
    margin-top: 50px;
}
body {
    background-color: #EFEFEF;
}
.layui-icon {
    color: #D2D2D2;
}

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>登陸</title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
    <script src="https://www.layuicdn.com/layui/layui.js"></script>
    <script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <link rel="stylesheet" href="/css/login.css">
    <link  rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://unpkg.com/axios@0.21.1/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
    <div class="login-form">
        <div class="login-title">后臺管理系統</div>
        <div class="layui-form">
            <div class="layui-form-item">
                <div class="input-div">
                    <i class="layui-icon layui-icon-username"></i>
                    <input type="text" name="username" v-model="user.username" 
                    lay-verify="title" @focus="focusCss('input-div')"
                     @blur="blurCss('input-div')" autocomplete="off"
                      placeholder="用戶名" class="layui-input" >
                </div>
            </div>
            <div class="layui-form-item">
                <div class="input-div2">
                    <i class="layui-icon layui-icon-password"></i>
                    <input type="password" name="username" v-model="user.password"  
                     lay-verify="title" @focus="focusCss('input-div2')" 
                     @blur="blurCss('input-div2')" autocomplete="off" 
                     placeholder="密碼" class="layui-input" >
                </div>
            </div>
            <div class="layui-form-item">
                <button type="button" style="width: 100%;"
                 class="layui-btn" @click="login">登陸</button>
            </div>
        </div>
    </div>
</div>
<script>
    var vm = new Vue({
        el:"#app",
        data:{
            user:{
                username:null,
                password:null
            }
        },
        methods:{
        	//登陸按鈕設定了@click=“login”,點擊就會呼叫此方法
            login(){
                let that = this;
                if(vm.user.username == null || vm.user.username == ""){
                    this.$message.error("請填寫用戶名");
                    return;
                }
                if(vm.user.password == null || vm.user.password == ""){
                    this.$message.error("請填寫密碼");
                    return;
                }
                //post請求發送賬號密碼
                axios({
                    url:"user/login",
                    method: "post",
                    headers:{
                        "Content-Type": "application/json"
                    },
                    data:JSON.stringify(vm.user)
                }).then(res => {
                   console.log("回傳結果",res.data);
                })
            },
            // 聚焦和失焦事件
            focusCss(name){
                $("."+name).css("border"," 1px solid #D2D2D2 ");
            },
            blurCss(name){
                $("."+name).css("border"," 1px solid #eee ");
            }
        }
    })
</script>
</body>
</html>

請求方式采用了axios,如果后面要接觸了前后端分離專案,可能就會了解到axios

controller檔案夾中撰寫登陸代碼和頁面跳轉

新建一個LoginController類,跳轉到login.html是依靠yml中設定thymeleaf配置
跳轉到templates/login.html頁面的

import com.github.pagehelper.util.StringUtil;
import com.macro.entity.UserEntity;
import com.macro.service.UserService;
import com.macro.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("login")
    public String login(){
        //依靠thymeleaf的映射,跳轉到templates/login.html
        return "login";
    }

    @PostMapping("user/login")
    @ResponseBody
    public Result login(@RequestBody UserEntity user){
//            判斷傳過來是否為空
        if(user == null || StringUtil.isEmpty(user.getUsername()) || 
        						StringUtil.isEmpty(user.getPassword())){
            return Result.error("賬號或者密碼不能為空");
        }
        //通過用戶名查詢
        UserEntity entity =   userService.findByUserName(user.getUsername());
        //為空則回到
        if(entity == null){
            return Result.error("賬號不存在!");
        }

        if(!entity.getPassword().equals(user.getPassword())){
            return Result.error("密碼錯誤!");
        }
        return Result.success();
    }
}


UserService介面添加findByUserName方法

//findByUserName方法,通過用戶名近些年剛擦黑訊
UserEntity findByUserName(String username);

UserServiceImpl 實作findByUserName方法

 @Autowired
    private UserDao userDao;

    @Override
    public UserEntity findByUserName(String username) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return userDao.selectOne(wrapper);
    }

啟動訪問:http://127.0.0.1:8086/login

我資料庫設定的賬號為:macro 密碼為:123456
在這里插入圖片描述
登陸成功code:200 失敗為code:400,工具類Result中默認設定的成功:200 失敗為: 400
在這里插入圖片描述

ifame的 index.html

登陸算是做好了,開始弄index.html
默認展示main.html,data中設定了./main.html,代碼里面一些 注解記得看一下,不能面面俱到,只能通過注解
描述一些關鍵的東西

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>后臺管理頁面</title>
    <link rel="stylesheet" href="https://unpkg.com/layui@2.6.8/dist/css/layui.css">
    <script src="https://unpkg.com/layui@2.6.8/dist/layui.js"></script>
    <link rel="stylesheet" type="text/css" href="css/layui-admin.css"/>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
</head>
<body>
<div id="rapp">
    <div class="layui-layout-admin " >
        <!--頭部-->
        <div class="layui-header layui-admin-border" style="background-color: #ffffff !important;">
            <div class="layui-logo" style="background-color: #001529 !important;"><a href="" style="color:#fff">無術同學</a></div>

            <ul class="layui-nav layui-layout-left" style="line-height: 60px;">
		  <span class="layui-breadcrumb">
		    <a href="">設定</a>
		    <a><cite>{{val}}</cite></a>
		  </span>
            </ul>
            <ul class="layui-nav layui-layout-right ">
                <li class="layui-nav-item">
                    <a  style="color:black"><img src="http://img.treebreezes.top/macro.jpg" class="layui-nav-img">無術同學</a>
                    <dl class="layui-nav-child">
                        <dd><a href="info.html">基本資料</a></dd>
                        <dd @click="logout"><a>退出</a></dd>
                    </dl>
                </li>
            </ul>
        </div>
        <!--左側-->
        <div class="layui-side layui-bg-black" style="background-color: #001529 !important;">
            <div class="layui-side-scroll">
                <ul class="layui-nav layui-nav-tree" lay-filter="hbkNavbar">
                    <li class="layui-nav-item" style="background-color: #001529 !important;">
                        <a href="javascript:;" > <i class="layui-icon layui-icon-set"> 設定</i></a>
                        <dl class="layui-nav-child" >
                            <dd><a href="./sysUser.html">管理員管理</a></dd>
                        </dl>
                    </li>
                </ul>
            </div>
        </div>
        <!--中間主體-->
        <div class="layui-body layui-bg-gray" id="container">
            <iframe scrolling="yes"
                    frameborder="0"
                    style="width:100%;overflow:visible;background:#fff; z-index: 50;height: 760px;" :src="main"></iframe>
        </div>
        <!--底部-->
        <div class="layui-footer">
            <center>Springboot + redis + shiro 動態權限管理系統  <font color="red">無術同學</font></center>
        </div>
    </div>
</div>
<script>
    var vm =  new Vue({
        el: '#rapp',
        data: {
            main:"./main.html",
            val:""
        },
        methods:{
            logout(){
            	//退出介面:訪問的是 127.0.0.1/logout
                window.location = "/logout"
            }
        },
        update:function(){
            console.log("###");
        }
    });
    //iframe自適應
    $(window).on('resize', function() {
        var $content = $('.content');
        $content.height($(this).height() - 154);
        $content.find('iframe').each(function() {
            $(this).height($content.height());
        });
    }).resize();
    //這塊是頁面跳轉的關鍵,動態目錄時會換掉
    $(document).ready(function(){
        $("dd>a").click(function (e) {
            e.preventDefault();
            vm.val = $(this).text();
            vm.main = $(this).attr("href")
        });
    });
</script>
</body>
</html>

新建main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    你好,我是無術同學!
</body>
</html>

LoginController類添加logout介面,可跳轉到login.html

 @GetMapping("logout")
    public String logout(){
        //退出跳到login.html頁面
        return "login";
    }

修改login.html

that.$messageelement ui的彈框,用來提示的

//請求user/login的方法改成
axios({
   url:"user/login",
   method: "post",
   headers:{  "Content-Type": "application/json"  },
   data:JSON.stringify(vm.user)
   }).then(res => {
   //此處為新加代碼
       if(res.data.code == 200){
           that.$message({message:"登陸成功", type: 'success'});
           window.location = "/"
       }else {
           that.$message.error(res.data.msg);
       }
       
   })

訪問地址:http://127.0.0.1:8086/login
在這里插入圖片描述
以上index.html的配置便好了,可以加入一些模塊了,比如管理員模塊

管理員模塊

新建sysUser.html

templates檔案夾下新建sysUser.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/layui-admin.css"/>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
    <link rel="stylesheet" type="text/css" href="css/layui-admin.css"/>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
    <script src="https://unpkg.com/axios@0.21.1/dist/axios.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="common.js"></script>
    <style>
        tbody > tr {
            height: 50px;
        }

    </style>
</head>
<body >
<div id="app">
    <div class="layui-bg-gray panel" >
        <div class="layui-card   panel-height">
            <div class="layui-card-header card-header" >
                <div class="layui-form-item" style="line-height: 60px;">
                    <div class="layui-inline">
                        <label class="layui-form-label">昵稱 </label>
                        <div class="layui-input-inline">
                            <input type="text" name="email" class="layui-input" v-model="param.niceName">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">用戶名:</label>
                        <div class="layui-input-inline">
                            <input type="text" name="email" class="layui-input" v-model="param.username">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="button" class="layui-btn " @click="reload"><i class="layui-icon layui-icon-search"></i></button>
                    </div>
                </div>
            </div>
            <div class="layui-card-body">
                <button type="button" class="layui-btn" @click="add">新增</button>
                <button type="button" class="layui-btn layui-btn-normal" @click="update">修改</button>
                <button type="button" class="layui-btn layui-btn-danger" @click="del">洗掉</button>
                <table class="layui-hide" id="table"></table>
            </div>
        </div>
    </div>

    <el-dialog :title="title" :visible.sync="show" width="30%">
        <div class="layui-form"   lay-filter="sex">
            <div class="layui-form-item">
                <label class="layui-form-label">昵稱</label>
                <div class="layui-input-inline">
                    <input type="text" name="title" required   placeholder="請輸入昵稱" v-model="user.niceName"  autocomplete="off" class="layui-input"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">賬號</label>
                <div class="layui-input-inline">
                    <input type="text" name="title" required   placeholder="請輸入賬號" v-model="user.username" autocomplete="off" class="layui-input"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密碼</label>
                <div class="layui-input-inline">
                    <input type="password" name="password" required  placeholder="請輸入密碼" v-model="user.password" autocomplete="off" class="layui-input"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">性別 </label>
                <div class="layui-input-inline">
                    <el-select  v-model="user.sex"  placeholder="請選擇">
                        <el-option value="0" key="0" label=""></el-option>
                        <el-option value="1" key="1" label=""></el-option>
                    </el-select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">頭像 </label>
                <div class="layui-input-block">
                    <el-upload class="avatar-uploader" show-file-list="false" action="upload/img" :on-success="success">
                        <img v-if="user.avatar" :src="user.avatar" class="avatar">
                    </el-upload>
                </div>
            </div>
        </div>
        <div slot="footer" class="dialog-footer" >
            <button type="button" class="layui-btn" @click="saveOrUpdate">確定</button>
            <button type="button" class="layui-btn layui-btn-primary" @click="cannel">取消</button>
        </div>
    </el-dialog>


</div>
<script src="https://www.layuicdn.com/layui/layui.js"></script>
<script src="js/sysUser.js"></script>
</body>
</html>

新建common.js

static檔案夾下新建common.js

function ids(){
    var arr =new Array();
    var res = layui.table.checkStatus('table');
    if(res.data!= null && res.data.length > 0){
        for (let i = 0; i < res.data.length; i++) {
            arr[i] = res.data[i].id;
        }
    }
    return arr;
}
function alert(msg){
    layer.msg(msg);
}

新建sysUser.js

sysUser.html下方有個引入sysUser.js的配置,src設定的為js/sysUser.js
js前面沒有添加/ ,這是一個相對路徑 ,

<script src="js/sysUser.js"></script>

static下新建一個js檔案夾,然后再js檔案夾中新建sysUser.js
mounted在初始化的時候會加載一次,類似$(function(){ })
templet的寫法是可以在Layui中看到答案的,d相當于當前回圈中的一條資料

var vm = new Vue({
    el:"#app",
    //初始化加載
    mounted(){
        layui.use('table', function(){
            var table = layui.table;
            table.render({
                elem: '#table'
                ,cellMinWidth: 80
                ,url:'sysUser/list'
                ,cols: [[
                    {type:'checkbox'}
                    ,{field:'id',  title: 'id' }
                    ,{field:'niceName',  title: '昵稱' }
                    ,{field:'username',  title: '用戶名'}
                    ,{field:'sex',  title: '性別',
                        templet: '<div> <span>{{d.sex == null?"未知":d.sex==0?"男":"女"}}</span> </div>'
                    }
                    ,{field: 'avatar', title:'頭像',
                        templet: '<div> <img style="height: 30px" src="{{d.avatar}}" > </div>'
                    }
                ]]
                ,page: true
            });
        });
    },
    data:{
        user:{
            niceName:null,
            username:null,
            password:null,
            sex:"",
            avatar:""
        },
        show:false,
        title:"新增用戶",
        param:{
            niceName:"",
            username:""
        }
    },

    methods:{
        //查詢+重新加載資料
        reload(){
            layui.use('table', function () {
                var table = layui.table;
                table.reload('table', {
                    url: 'sysUser/list'
                    ,where: vm.param
                });
            });
            vm.show = false;
        },
        add(){
            vm.show = true;
            //初始化
            vm.user = {
                niceName:null,
                username:null,
                password:null,
                sex:"0",
                avatar:null
            };
            vm.title= "新增用戶";
        },
        update(){
            let data = ids();
            if(data == null || data.length == 0 || data.length  > 1){
                alert("請選擇一條資料!")
                return;
            }
            vm.show = true;
            vm.user = {};
            vm.info(data[0]);
            vm.title= "修改用戶";
        },
        del(){
            let that = this;
            let data = ids();
            if(data == null || data.length == 0){
                alert("請選擇!")
                return;
            }
            layer.open({
                title: '洗掉'
                ,content: '是否洗掉資料',
                btn:['確定','取消'],
                yes: function(index, layero){
                    axios({
                        url:"sysUser/del",
                        method: "post",
                        headers:{
                            "Content-Type": "application/json"
                        },
                        data:JSON.stringify(data)
                    }).then(res =>{
                        if(res.data.code == 200){
                            that.$message({message:"洗掉成功", type: 'success'});
                            vm.reload();
                        }else {
                            that.$message.error("洗掉失敗");
                        }
                    });
                    layer.close(index)
                }
            });



        },
        //保存或者更新
        saveOrUpdate(){
            let state = vm.user.id == null|| vm.user.id == "";
            let url = state ?"sysUser/add":"sysUser/update"
            axios({
                url:url,
                method: "post",
                headers:{
                    "Content-Type": "application/json"
                },
                data:JSON.stringify(vm.user)
            }).then(res =>{
                if(res.data.code == 200){
                    this.$message({message: state?"添加成功":"修改成功", type: 'success'});
                    vm.reload();
                }else{
                    this.$message.error(state?'新增失敗':"修改失敗");
                }
            });

        },
        cannel(){
            vm.show = false;
        },
        //查詢單條
        info(id){
            axios({
                method:"get",
                url: "sysUser/info/" + id
            }).then(res =>{
                if(res.data.code == 200){
                    vm.user = res.data.data;
                    vm.user.sex = vm.user.sex.toString();
                }

            })
        },
        success(res, file){
            vm.user.avatar = res.data;
        }

    }

})

一些重要的點

我默認在add或者update方法中都會去初始化資料為空,這樣重復操作資料就不會造成資料例外
JSON.stringify 這個是將物件轉化成json資料,好方便后端接收
addupdate 中有一個ids()方法,這個是common.js中的方法,用戶獲取table表單id值,后面每個增刪改查的頁面都有有這個的影子,所有把這個東西抽取出來了,其實head頭部的那些參考也可以
抽取出來,更加的靈活一些

新建 PageEntity

macro包下新建一個Vo
創建PageEntity

import lombok.Data;
//后面帶查詢的都會用到分頁資料
@Data
public class PageEntity {
//  頁數
    private Integer page;
//每頁數量
    private Integer limit;
}

Vo下新建UserParam

將引數封裝起來對以后的開發有好處,只需要改動UserParam類,然后去xml添加對應的sql即可,
無需改動servicedao代碼了,一個開發小技巧送給你

//繼承PageEntity
@Data
public class UserParam extends PageEntity {
    //昵稱
    private String niceName;
    //賬號
    private String username;
}

新增sysUserController

除了findByParam方法,其余的新增修改洗掉都是mybatis plus提供的

import com.macro.Vo.UserParam;
import com.macro.entity.UserEntity;
import com.macro.service.UserService;
import com.macro.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("sysUser")
public class sysUserController {
    @Autowired
    private UserService userService;

    @GetMapping("list")
    public Result list(UserParam param){
        Result result = userService.findByParam(param);
        return result;
    }

    @PostMapping("add")
    public Result add(@RequestBody UserEntity user){
        //密碼加密
        boolean save = userService.save(user);
        if(save){
            return Result.success();
        }
        return Result.error("添加失敗");
    }

    @GetMapping("info/{id}")
    public Result info(@PathVariable("id") Integer id){
        UserEntity userEntity = userService.getById(id);
        return Result.success(userEntity);
    }


    @PostMapping("update")
    public Result update(@RequestBody UserEntity user){
        boolean type = userService.updateById(user);
        return type ? Result.success() : Result.error("更新失敗");
    }

    @PostMapping("del")
    public Result del(@RequestBody String[] ids){
        if(ids.length > 0){
            boolean type = userService.removeByIds(Arrays.asList(ids));
            return type ? Result.success() : Result.error("洗掉失敗");
        }
        return  Result.success();
    }


}

UserService新增 findByParam

    Result findByParam(UserParam param);

UserServiceImpl新增 findByParam方法的實作

PageHelper是分頁插件工具,舒舒服服寫代碼!Result.success報錯是因為還沒改,
后面寫了改動

 @Override
    public Result findByParam(UserParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        List<UserEntity> list = userDao.findByParam(param);
        PageInfo<UserEntity> pageInfo = new PageInfo<>(list);
        return Result.success(0,pageInfo.getTotal(),list);
    }

UserDao新增findByParam

	//傳入param物體類引數
    List<UserEntity> findByParam(@Param("param")UserParam param);

UserDao.xml 代碼

like模糊查詢,防注入

<?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="com.macro.dao.UserDao">
    <select id="findByParam" resultType="com.macro.entity.UserEntity">
        select * from sys_user
        where 1=1
        <if test="param.niceName != null and param.niceName != ''">
            and   nice_name like  CONCAT('%',#{param.niceName,jdbcType=VARCHAR},'%')
        </if>
        <if test="param.username != null and param.username != ''">
            and   username like  CONCAT('%',#{param.username,jdbcType=VARCHAR},'%')
        </if>
    </select>
</mapper>

Result類改動

import lombok.Data;

@Data
public class Result {
    private Integer code;
    private String msg;
    private Object data;
    private Long count;

    Result(Integer code,String msg,Object data,Long count){
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.count = count;
    }

    public static Result success(Object data){
        return new Result(200,"成功",data,null);
    }
    public static Result success(){
        return new Result(200,"成功",null,null);
    }
    public static Result success(Integer code,Long count,Object data){
        return new Result(code,"成功",data,count);
    }

    public static Result error(Integer code,String msg){
        return new Result(code,msg,null,null);
    }

    public static Result error(String msg){
        return new Result(400,msg,null,null);
    }
}

啟動之后點擊管理員管理,出現的頁面就是這樣了,除了圖片上傳基本就沒問題了
在這里插入圖片描述

圖片上傳

sysUser.html 頭像上傳采用了elemen uiel-upload上傳控制元件,action設定了圖片上傳的請求地址
在這里插入圖片描述

sysUser.js

這一塊有一個圖片處理,有興趣可以列印看一下回傳了什么
在這里插入圖片描述

新建類

添加這三個類
在這里插入圖片描述

FileUploadUtil


import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class FileUploadUtil {
    public static String BasePath = "";
    private static String LINUXPATH = "/classmate/upload/";
    private static String MACPATH = "/Users/classmate/upload/";
    private static String WINDOWSPATH = "C:/classmate/upload/";
    //根目錄
    private static String ROOT = "upload/";

    static {
        initBasePath();
    }

    /**
     * 系統初始化上傳根目錄
     */
    public static void initBasePath() {
        BasePath = getBasePath();
        File BasePathFile = new File(BasePath);
        if (!BasePathFile.exists()) {
            BasePathFile.mkdirs();
        }
    }

    /**
     *   獲取當前環境的路徑
     */
    public static String getBasePath() {
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os != null && os.toLowerCase().indexOf("linux") > -1) {
            return LINUXPATH;
        } else if (os != null && os.toLowerCase().indexOf("mac") > -1) {
            return MACPATH;
        } else {
            return WINDOWSPATH;
        }
    }

    /**
     *
     * @param file 流
     * @param folderName 檔案夾名稱, 如: C:/classmate/upload/ (folderName檔案名)
     * @return
     */
    public static String uploadFile(MultipartFile file, String folderName){
        FileOutputStream fot = null;
        //獲取上傳到的路徑地址
        String path = getBasePath();
        path = path + folderName;

        //檔案名稱
        String filePath = getFilePath(file,path);
        File dest = new File(path + "/" + filePath);
        try {
            dest.createNewFile();//創建一個檔案
            fot = new FileOutputStream(dest);
            byte[] bytes = file.getBytes();
            fot.write(bytes);

            //根目錄: upload/ + 自定義目錄: user/  + 檔案名: xxxx.jpg
            return ROOT + folderName + "/" +filePath;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            if(fot != null){
                try {
                    fot.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param path 檔案夾名字
     * @param file     file檔案
     * @return
     */
    private static String getFilePath(MultipartFile file, String path) {
        //生成檔案名稱(防止重復)
        long date = System.currentTimeMillis();
        //檢測是否創建
        if (!new File(path).isDirectory()) {
            new File(path).mkdirs();
        }
        //截取檔案后綴 如:xxx.jpg xxx.png
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        //拼接新的檔案名稱
        String name = date + suffix;
        //生成路徑加上名字
        return  name;
    }

}

新建 WebConfig

import com.macro.utils.FileUploadUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //設定訪問路徑為:127.0.0.1:8080/upload/**
        //映射路徑:FileUploadUtil.getBasePath() 獲取的路徑
        registry.addResourceHandler("/upload/**").addResourceLocations("file:///" + FileUploadUtil.getBasePath());
    }
}

新建UploadController

import com.macro.utils.FileUploadUtil;
import com.macro.utils.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 檔案上傳controller
 */
@RestController
@RequestMapping("upload")
public class UploadController {

    //圖片上傳
    @PostMapping("img")
    public Result upload(MultipartFile file){
        //user:檔案加名稱,圖片或者檔案會放在user檔案夾
        String imgPath = FileUploadUtil.uploadFile(file, "user");
        return  Result.success(imgPath);
    }
}

檔案上傳

檔案上傳只是保存了部分路徑,如:upload/user/xxxx.png
無視專案名稱的更改和埠的更改,直接可以訪問
運行看一下效果,完全沒問題
在這里插入圖片描述

總結

邏輯比較簡單,就是代碼量比較多,下面這張圖大概的意思就是,請求/login通過controller跳轉到login,
只不過通過thymeleaf的幫助,去尋找templates檔案夾下的login.html檔案,原本相加info.html,
但是篇幅太長了,留到下一篇吧
在這里插入圖片描述

原始碼

在公眾號內發送后臺即可獲取原始碼和資料庫
請添加圖片描述

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/305219.html

標籤:其他

上一篇:Formik使用教程以及開發中遇到的問題

下一篇:哇~會動的頁面來了! -----小米官網

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • vue移動端上拉加載

    可能做得過于簡單或者比較low,請各位大佬留情,一起探討技術 ......

    uj5u.com 2020-09-10 04:38:07 more
  • 優美網站首頁,頂部多層導航

    一個個人用的瀏覽器首頁,可以把一下常用的網站放在這里,平常打開會比較方便。 第一步,HTML代碼 <script src=https://www.cnblogs.com/szharf/p/"js/jquery-3.4.1.min.js"></script> <div id="navigate"> <ul> <li class="labels labels_1"> ......

    uj5u.com 2020-09-10 04:38:47 more
  • 頁面為要加<!DOCTYPE html>

    最近因為寫一個js函式,需要用到$(window).height(); 由于手寫demo的時候,過于自信,其實對前端方面的認識也不夠體系,用文本檔案直接敲出來的html代碼,第一行沒有加上<!DOCTYPE html> 導致了$(window).height();的結果直接是整個document的高 ......

    uj5u.com 2020-09-10 04:38:52 more
  • WordPress網站程式手動升級要做好資料備份

    WordPress博客網站程式在進行升級前,必須要做好網站資料的備份,這個問題良家佐言是遇見過的;在剛開始接觸WordPress博客程式的時候,因為升級問題和博客網站的修改的一些嘗試,良家佐言是吃盡了苦頭。因為購買的是西部數碼的空間和域名,每當佐言把自己的WordPress博客網站搞到一塌糊涂的時候 ......

    uj5u.com 2020-09-10 04:39:30 more
  • WordPress程式不能升級為5.4.2版本的原因

    WordPress是一款個人博客系統,受到英文博客愛好者和中文博客愛好者的追捧,并逐步演化成一款內容管理系統軟體;它是使用PHP語言和MySQL資料庫開發的,用戶可以在支持PHP和MySQL資料庫的服務器上使用自己的博客。每一次WordPress程式的更新,就會牽動無數WordPress愛好者的心, ......

    uj5u.com 2020-09-10 04:39:49 more
  • 使用CSS3的偽元素進行首字母下沉和首行改變樣式

    網頁中常見的一種效果,首字改變樣式或者首行改變樣式,效果如下圖。 代碼: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, ......

    uj5u.com 2020-09-10 04:40:09 more
  • 關于a標簽的講解

    什么是a標簽? <a> 標簽定義超鏈接,用于從一個頁面鏈接到另一個頁面。 <a> 元素最重要的屬性是 href 屬性,它指定鏈接的目標。 a標簽的語法格式:<a href=https://www.cnblogs.com/summerxbc/p/"指定要跳轉的目標界面的鏈接">需要展示給用戶看見的內容</a> a標簽 在所有瀏覽器中,鏈接的默認外觀如下: 未被訪問的鏈接帶 ......

    uj5u.com 2020-09-10 04:40:11 more
  • 前端輪播圖

    在需要輪播的頁面是引入swiper.min.js和swiper.min.css swiper.min.js地址: 鏈接:https://pan.baidu.com/s/15Uh516YHa4CV3X-RyjEIWw 提取碼:4aks swiper.min.css地址 鏈接:https://pan.b ......

    uj5u.com 2020-09-10 04:40:13 more
  • 如何設定html中的背景圖片(全屏顯示,且不拉伸)

    1 <style>2 body{background-image:url(https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture); 3 background-size:cover;background ......

    uj5u.com 2020-09-10 04:40:16 more
  • Java學習——HTML詳解(上)

    HTML詳解 初識HTML Hyper Text Markup Language(超文本標記語言) 1 <!--DOCTYPE:告訴瀏覽器我們要使用什么規范--> 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <!--meta 描述性的標簽,描述一些 ......

    uj5u.com 2020-09-10 04:40:33 more
最新发布
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 07:59:23 more
  • 生產事故-走近科學之消失的JWT

    入職多年,面對生產環境,盡管都是小心翼翼,慎之又慎,還是難免捅出簍子。輕則滿頭大汗,面紅耳赤。重則系統停擺,損失資金。每一個生產事故的背后,都是寶貴的經驗和教訓,都是專案成員的血淚史。為了更好地防范和遏制今后的各類事故,特開此專題,長期更新和記錄大大小小的各類事故。有些是親身經歷,有些是經人耳傳口授 ......

    uj5u.com 2023-04-18 07:55:04 more
  • 記錄--Canvas實作打飛字游戲

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 打開游戲界面,看到一個畫面簡潔、卻又富有挑戰性的游戲。螢屏上,有一個白色的矩形框,里面不斷下落著各種單詞,而我需要迅速地輸入這些單詞。如果我輸入的單詞與螢屏上的單詞匹配,那么我就可以獲得得分;如果我輸入的單詞錯誤或者時間過長,那么我就會輸 ......

    uj5u.com 2023-04-04 08:35:30 more
  • 了解 HTTP 看這一篇就夠

    在學習網路之前,了解它的歷史能夠幫助我們明白為何它會發展為如今這個樣子,引發探究網路的興趣。下面的這張圖片就展示了“互聯網”誕生至今的發展歷程。 ......

    uj5u.com 2023-03-16 11:00:15 more
  • 藍牙-低功耗中心設備

    //11.開啟藍牙配接器 openBluetoothAdapter //21.開始搜索藍牙設備 startBluetoothDevicesDiscovery //31.開啟監聽搜索藍牙設備 onBluetoothDeviceFound //30.停止監聽搜索藍牙設備 offBluetoothDevi ......

    uj5u.com 2023-03-15 09:06:45 more
  • canvas畫板(滑鼠和觸摸)

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>canves</title> <style> #canvas { cursor:url(../images/pen.png),crosshair; } #canvasdiv{ bo ......

    uj5u.com 2023-02-15 08:56:31 more
  • 手機端H5 實作自定義拍照界面

    手機端 H5 實作自定義拍照界面也可以使用 MediaDevices API 和 <video> 標簽來實作,和在桌面端做法基本一致。 首先,使用 MediaDevices.getUserMedia() 方法獲取攝像頭媒體流,并將其傳遞給 <video> 標簽進行渲染。 接著,使用 HTML 的 < ......

    uj5u.com 2023-01-12 07:58:22 more
  • 記錄--短視頻滑動播放在 H5 下的實作

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 短視頻已經無數不在了,但是主體還是使用 app 來承載的。本文講述 H5 如何實作 app 的視頻滑動體驗。 無聲勝有聲,一圖頂百辯,且看下圖: 網址鏈接(需在微信或者手Q中瀏覽) 從上圖可以看到,我們主要實作的功能也是本文要講解的有: ......

    uj5u.com 2023-01-04 07:29:05 more
  • 一文讀懂 HTTP/1 HTTP/2 HTTP/3

    從 1989 年萬維網(www)誕生,HTTP(HyperText Transfer Protocol)經歷了眾多版本迭代,WebSocket 也在期間萌芽。1991 年 HTTP0.9 被發明。1996 年出現了 HTTP1.0。2015 年 HTTP2 正式發布。2020 年 HTTP3 或能正... ......

    uj5u.com 2022-12-24 06:56:02 more
  • 【HTML基礎篇002】HTML之form表單超詳解

    ??一、form表單是什么

    ??二、form表單的屬性

    ??三、input中的各種Type屬性值

    ??四、標簽 ......

    uj5u.com 2022-12-18 07:17:06 more