溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用SSM+BootStrap實現(xiàn)增刪改查和頭像上傳效果

發(fā)布時間:2021-06-29 13:42:55 來源:億速云 閱讀:262 作者:chen 欄目:web開發(fā)

這篇文章主要講解了“使用SSM+BootStrap實現(xiàn)增刪改查和頭像上傳效果”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“使用SSM+BootStrap實現(xiàn)增刪改查和頭像上傳效果”吧!

先看界面

使用SSM+BootStrap實現(xiàn)增刪改查和頭像上傳效果

點擊編輯之后

使用SSM+BootStrap實現(xiàn)增刪改查和頭像上傳效果

具體代碼請往下看

一、jsp界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<link
    href="${pageContext.request.contextPath }/bootstrap-3.3.7-dist/css/bootstrap.css"
    rel="stylesheet"></link>
<link
    href="${pageContext.request.contextPath }/bootstrap-fileinput/css/fileinput.css"
    media="all" rel="stylesheet" type="text/css" />
<link
    href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
    media="all" rel="stylesheet" type="text/css" />
<link
    href="${pageContext.request.contextPath }/bootstrap-fileinput/themes/explorer-fa/theme.css"
    media="all" rel="stylesheet" type="text/css" />
<link
    href="${pageContext.request.contextPath }/bootstrap-table-develop/docs/dist/bootstrap-table.css"
    rel="stylesheet"></link>
<script
    src="${pageContext.request.contextPath }/bootstrap-3.3.7-dist/js/jquery.js"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-fileinput/js/plugins/sortable.js"
    type="text/javascript"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-fileinput/js/fileinput.js"
    type="text/javascript"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-fileinput/js/locales/fr.js"
    type="text/javascript"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-fileinput/js/locales/es.js"
    type="text/javascript"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-fileinput/themes/explorer-fa/theme.js"
    type="text/javascript"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-fileinput/themes/fa/theme.js"
    type="text/javascript"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-fileinput/js/locales/zh.js"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-table-develop/docs/dist/bootstrap-table.js"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-table-develop/docs/dist/js/bootstrap-table-locale-all.js"></script>
<script
    src="${pageContext.request.contextPath }/bootstrap-table-develop/src/locale/bootstrap-table-zh-CN.js"></script>
<body>
    <table id="result" class="table table-hover"
        style="text-align: center;">
        <thead style="text-align: center;">
            <th data-field="stuid">學(xué)生編號</th>
            <th data-field="stuname">學(xué)生姓名</th>
            <th data-field="classes.classname">班級名稱</th>
            <th data-field="userimage" data-formatter="image">頭像</th>
            <th data-field="state" data-formatter="state">狀態(tài)</th>
            <th data-field="caozuo" data-formatter="toolbar">操作</th>
        </thead>
    </table>
    <form action="#" id="formid" onsubmit="return false"
        enctype="multipart/form-data">
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog"
            aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"
                            aria-hidden="true">×</button>
                        <h5 class="modal-title" id="myModalLabel">學(xué)生信息修改</h5>
                    </div>
                    <div class="modal-body">
                        學(xué)生編號:<input type="text" name="stuid" class="form-control" value=""
                            readonly="readonly" /><br> 學(xué)生姓名:<input type="text"
                            name="stuname" class="form-control" id="stuname" value=""><br>
                        所在班級:<select id="class" name="classesid" class="form-control">
                        </select> 當(dāng)前頭像:
                        <div>
                            <img alt="" style="width: 40px; height: 40px" id="img">
                        </div>
                        用戶頭像:
                        <div class="file-loading">
                            <input id="file-fr" name="file" type="file" multiple>
                        </div>

                        <input type="hidden" id="userimage" name="userimage" value="" />
                    </div>
                    <div class="modal-footer">
                        <button type="button" onclick="update()" class="btn btn-primary"
                            data-dismiss="modal">提交更改</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">關(guān)閉</button>
                    </div>
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal -->
        </div>
    </form>
</body>
<script>
    $('#file-fr').fileinput({
        theme : 'fa',
        language : 'zh',
        uploadAsync : true,//異步上傳
        uploadUrl : 'upload.do',
        allowedFileExtensions : [ 'jpg', 'png', 'gif', 'mp4' ],
        maxFileSize : 0,
        maxFileCount : 1
    }).on("fileuploaded", function(event, data) { //異步上傳成功結(jié)果處理
        $("#userimage").val(data.response.src);
    })
</script>
<script type="text/javascript">
    $(function() {
        $("#result").bootstrapTable({
            url : "selectAll.do",
            method : "post",
            cache : false,
            dataType : "json",
            contentType : "application/x-www-form-urlencoded",//post的方式提交的話需要寫
            toolbar : "#toolbar",
            toolbarAlign : "left",
            striped : true,
            pagination : true,
            sidePagination : "server",
            pageNumber : 1,
            pageSize : 5,
            pageList : [ 5, 10, 15 ],
            locale : "zh-CN",
            queryParamsType : "limit",
            queryParams : queryParams
        });
    });

    function queryParams(params) {
        var params = {
            pageSize : params.limit,
            pageCode : params.offset / params.limit + 1
        };
        return params;
    };
    function state(value, row, index) {
        if (row['state'] === 0) {
            return "正常";
        }
        if (row['state'] === 1) {
            return "鎖定";
        }
        return value;
    }
    function image(value, row, index) {
        return "<img src='"+row['userimage']+"' style='width:30px;height:30px;'/>";
    }
    /*操作按鈕*/
    function toolbar(value, row, index) {
        var element = "<button type='button' onclick='edit(" + row.stuid
                + ")' class='btn btn-info'>編輯</button>"
                + "<button type='button' onclick='del(" + row.stuid
                + ")' class='btn btn-danger'>刪除</button>"
                + "<button type='button' onclick='download(" + row.stuid
                + ")' class='btn btn-warning'>下載</button>";
        return element;
    }
    /*編輯按鈕,彈出模態(tài)框*/
    function edit(stuid) {
        $("#class option").remove();
        $("#formid")[0].reset();
        $.ajax({
            url : "editBystuid.do?stuid=" + stuid,
            type : "post",
            dataType : "json",
            success : function(data) {
                $('#myModal').modal('show');
                $("[name=stuid]").val(data[0].stuid);
                $("#stuname").val(data[0].stuname);
                $("#userimage").val(data[0].userimage);
                $("#img").attr('src', data[0].userimage);
                $("#class").append(
                        "<option value='"+data[0].calssesid+"'>"
                                + data[0].classes.classname + "</option>");
            }
        });
        $.ajax({
            url : "selectAllClass.do",
            type : "post",
            dataType : "json",
            success : function(data) {
                var obj = $("#class");
                for (var i = 0; i < data.length; i++) {
                    var op = "<option value='"+data[i].classesid+"'>"
                            + data[i].classname + "</option>";
                    obj.append(op);
                }
            }
        })
    };
    /*修改操作*/
    function update() {
        $.ajax({
            url : "updateBystuid.do",
            type : "get",
            dataType : "text",
            data : $("#formid").serialize(),
            success : function(data) {
                if (data == "ok") {
                    $("#result").bootstrapTable("refresh", {
                        url : "selectAll.do"
                    });
                } else if (data == "error") {
                    alert("修改失?。?quot;);
                }
            }
        });

    }
    /*刪除操作*/
    function del(stuid) {
        if (confirm('確定要刪除嗎?') == true) {
            $.ajax({
                url : "delBystuid.do?stuid=" + stuid,
                type : "post",
                dataType : "text",
                success : function(data) {
                    if (data == "ok") {
                        $("#result").bootstrapTable("refresh", {
                            url : "selectAll.do"
                        });
                    } else if (data == "error") {
                        alert("刪除失敗");
                    }
                }
            })
            return false;
        }
    }
    /*下載*/
    function download(stuid){
        if(confirm('確定要下載頭像?')==true){
            location.href="download.do?stuid="+stuid;
            /* $.ajax({
                url:"download.do?stuid="+stuid,
                type:"post",
                dataType:"json",
                success:function(data){

                }
            }); */
        }
    }
</script>
</html>

二、Controller層代碼

package com.llh.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.llh.entity.Student;
import com.llh.service.StudentService;

import net.sf.json.JSONArray;

@Controller
@Scope("prototype")
public class StudentController {

    @Resource
    private StudentService studentService;

    /**
     * 分頁查詢所有
     *
     * @param pageCode
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "selectAll", produces = "text/html;charset=utf-8")
    public @ResponseBody String selectAll(int pageCode, int pageSize) {
        PageHelper.startPage(pageCode, pageSize);
        List<Student> slist = studentService.selectAll();
        PageInfo<Student> spi = new PageInfo<Student>(slist);
        int count = (int) spi.getTotal();
        JSONArray json = JSONArray.fromObject(slist);
        String str = "{\"total\":" + count + ",\"rows\":" + json.toString() + "}";
        return str;
    }

    /**
     * 上傳
     *
     * @param request
     * @param file
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "upload")
    public @ResponseBody String upload(HttpServletRequest request, MultipartFile file)
            throws IllegalStateException, IOException {
        String name = file.getOriginalFilename();
        String path = request.getServletContext().getRealPath("/upload/");// 上傳保存的路徑
        String fileName = changeName(name);
        String rappendix = "upload/" + fileName;
        fileName = path + "\\" + fileName;
        File file1 = new File(fileName);
        file.transferTo(file1);
        String str = "{\"src\":\"" + rappendix + "\"}";
        return str;
    }

    public static String changeName(String oldName) {
        Random r = new Random();
        Date d = new Date();
        String newName = oldName.substring(oldName.indexOf('.'));
        newName = r.nextInt(99999999) + d.getTime() + newName;
        return newName;
    }

    /**
     * 編輯
     *
     * @param stuid
     * @param session
     * @return
     */
    @RequestMapping(value = "editBystuid", produces = "text/html;charset=utf-8")
    public @ResponseBody String editBystuid(Integer stuid) {
        System.out.println("編輯");
        Student s = studentService.selectByPrimaryKey(stuid);
        JSONArray json = JSONArray.fromObject(s);
        String js = json.toString();
        System.out.println(js);
        return js;
    }

    /**
     * 修改
     *
     * @param stuid
     * @param stuname
     * @return
     */
    @RequestMapping(value = "updateBystuid", produces = "text/html;charset=utf-8")
    public @ResponseBody String updateBystuid(@ModelAttribute Student s) {
        System.out.println("修改中");
        System.out.println(s.getStuname() + s.getStuid()+s.getUserimage());
        int a = studentService.updateByPrimaryKey(s);
        if (a != 0) {
            return "ok";
        }
        return "error";
    }

    /**
     * 下載
     *
     * @param stuid
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "download", produces = "text/html;charset=utf-8")
    public ResponseEntity<byte[]> download(Integer stuid,HttpServletRequest request) throws IOException {
        Student s = studentService.selectByPrimaryKey(stuid);
        String path=request.getServletContext().getRealPath("\\");
        String downpath = path+s.getUserimage();
        File file1=new File(downpath);
        //String downloadFileName=new String(downpath.getBytes("UTF-8"),"iso-8859-1");
        HttpHeaders heads=new HttpHeaders();
        heads.setContentDispositionFormData("attachment", downpath);
        heads.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file1), heads,HttpStatus.CREATED);
    }



}

三、dao層和service層實體類就掠過了

這里使用到的有自動生成實體類,Maven的分頁

具體操作請看首頁

感謝各位的閱讀,以上就是“使用SSM+BootStrap實現(xiàn)增刪改查和頭像上傳效果”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對使用SSM+BootStrap實現(xiàn)增刪改查和頭像上傳效果這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI