웹 프론트엔드 부트스트랩 튜토리얼 SSM+BootStrap을 사용하여 추가, 삭제, 수정, 확인 및 아바타 업로드 효과를 얻는 방법에 대한 간략한 설명

SSM+BootStrap을 사용하여 추가, 삭제, 수정, 확인 및 아바타 업로드 효과를 얻는 방법에 대한 간략한 설명

Jun 29, 2021 am 11:12 AM
bootstrap ssm 추가, 삭제, 수정 및 확인 아바타 업로드

本篇文章给大家通过示例介绍一下使用SSM+BootStrap实现增删改查和头像上传效果的方法。

SSM+BootStrap을 사용하여 추가, 삭제, 수정, 확인 및 아바타 업로드 효과를 얻는 방법에 대한 간략한 설명

【相关推荐:《bootstrap教程》】

先看界面

 点击编辑之后

具体代码请往下看

一、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">学生编号</th>
            <th data-field="stuname">学生姓名</th>
            <th data-field="classes.classname">班级名称</th>
            <th data-field="userimage" data-formatter="image">头像</th>
            <th data-field="state" data-formatter="state">状态</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>
                        <h4 class="modal-title" id="myModalLabel">学生信息修改</h4>
                    </div>
                    <div class="modal-body">
                        学生编号:<input type="text" name="stuid" class="form-control" value=""
                            readonly="readonly" /><br> 学生姓名:<input type="text"
                            name="stuname" class="form-control" id="stuname" value=""><br>
                        所在班级:<select id="class" name="classesid" class="form-control">
                        </select> 当前头像:
                        <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">关闭</button>
                    </div>
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal -->
        </div>
    </form>
</body>
<script>
    $(&#39;#file-fr&#39;).fileinput({
        theme : &#39;fa&#39;,
        language : &#39;zh&#39;,
        uploadAsync : true,//异步上传
        uploadUrl : &#39;upload.do&#39;,
        allowedFileExtensions : [ &#39;jpg&#39;, &#39;png&#39;, &#39;gif&#39;, &#39;mp4&#39; ],
        maxFileSize : 0,
        maxFileCount : 1
    }).on("fileuploaded", function(event, data) { //异步上传成功结果处理
        $("#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[&#39;state&#39;] === 0) {
            return "正常";
        }
        if (row[&#39;state&#39;] === 1) {
            return "锁定";
        }
        return value;
    }
    function image(value, row, index) {
        return "<img src=&#39;"+row[&#39;userimage&#39;]+"&#39; style=&#39;width:30px;height:30px;&#39;/>";
    }
    /*操作按钮*/
    function toolbar(value, row, index) {
        var element = "<button type=&#39;button&#39; onclick=&#39;edit(" + row.stuid
                + ")&#39; class=&#39;btn btn-info&#39;>编辑</button>"
                + "<button type=&#39;button&#39; onclick=&#39;del(" + row.stuid
                + ")&#39; class=&#39;btn btn-danger&#39;>删除</button>"
                + "<button type=&#39;button&#39; onclick=&#39;download(" + row.stuid
                + ")&#39; class=&#39;btn btn-warning&#39;>下载</button>";
        return element;
    }
    /*编辑按钮,弹出模态框*/
    function edit(stuid) {
        $("#class option").remove();
        $("#formid")[0].reset();
        $.ajax({
            url : "editBystuid.do?stuid=" + stuid,
            type : "post",
            dataType : "json",
            success : function(data) {
                $(&#39;#myModal&#39;).modal(&#39;show&#39;);
                $("[name=stuid]").val(data[0].stuid);
                $("#stuname").val(data[0].stuname);
                $("#userimage").val(data[0].userimage);
                $("#img").attr(&#39;src&#39;, data[0].userimage);
                $("#class").append(
                        "<option value=&#39;"+data[0].calssesid+"&#39;>"
                                + 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=&#39;"+data[i].classesid+"&#39;>"
                            + 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("修改失败!");
                }
            }
        });

    }
    /*删除操作*/
    function del(stuid) {
        if (confirm(&#39;确定要删除吗?&#39;) == 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(&#39;确定要下载头像?&#39;)==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(&#39;.&#39;));
        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을 사용하여 추가, 삭제, 수정, 확인 및 아바타 업로드 효과를 얻는 방법에 대한 간략한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

부트 스트랩의 수직 중심을 수행하는 방법 부트 스트랩의 수직 중심을 수행하는 방법 Apr 07, 2025 pm 03:21 PM

부트 스트랩을 사용하여 수직 센터링을 구현하여 : Flexbox Method : D-Flex, 정당화 컨텐츠 중심 및 정렬 중심 센터 클래스를 사용하여 Flexbox 컨테이너에 요소를 배치하십시오. Align-Items-Center 클래스 방법 : Flexbox를 지원하지 않는 브라우저의 경우 상위 요소의 높이가 정의 된 경우 Align-Items 중심 클래스를 사용하십시오.

부트 스트랩 버튼을 사용하는 방법 부트 스트랩 버튼을 사용하는 방법 Apr 07, 2025 pm 03:09 PM

부트 스트랩 버튼을 사용하는 방법? 부트 스트랩 CSS를 소개하여 버튼 요소를 만들고 부트 스트랩 버튼 클래스를 추가하여 버튼 텍스트를 추가하십시오.

부트 스트랩 크기를 조정하는 방법 부트 스트랩 크기를 조정하는 방법 Apr 07, 2025 pm 03:18 PM

부트 스트랩에서 요소의 크기를 조정하려면 다음을 포함하여 차원 클래스를 사용할 수 있습니다.

부트 스트랩을위한 프레임 워크를 설정하는 방법 부트 스트랩을위한 프레임 워크를 설정하는 방법 Apr 07, 2025 pm 03:27 PM

부트 스트랩 프레임 워크를 설정하려면 다음 단계를 따라야합니다. 1. CDN을 통해 부트 스트랩 파일 참조; 2. 자신의 서버에서 파일을 다운로드하여 호스팅하십시오. 3. HTML에 부트 스트랩 파일을 포함; 4. 필요에 따라 Sass/Less를 컴파일하십시오. 5. 사용자 정의 파일을 가져옵니다 (선택 사항). 설정이 완료되면 Bootstrap의 그리드 시스템, 구성 요소 및 스타일을 사용하여 반응 형 웹 사이트 및 응용 프로그램을 만들 수 있습니다.

부트 스트랩에 사진을 삽입하는 방법 부트 스트랩에 사진을 삽입하는 방법 Apr 07, 2025 pm 03:30 PM

Bootstrap에 이미지를 삽입하는 방법에는 여러 가지가 있습니다. HTML IMG 태그를 사용하여 이미지를 직접 삽입하십시오. 부트 스트랩 이미지 구성 요소를 사용하면 반응 형 이미지와 더 많은 스타일을 제공 할 수 있습니다. 이미지 크기를 설정하고 IMG-Fluid 클래스를 사용하여 이미지를 적응할 수 있도록하십시오. IMG 통과 클래스를 사용하여 테두리를 설정하십시오. 둥근 모서리를 설정하고 IMG 라운드 클래스를 사용하십시오. 그림자를 설정하고 그림자 클래스를 사용하십시오. CSS 스타일을 사용하여 이미지를 조정하고 배치하십시오. 배경 이미지를 사용하여 배경 이미지 CSS 속성을 사용하십시오.

부트 스트랩 검색 창을 얻는 방법 부트 스트랩 검색 창을 얻는 방법 Apr 07, 2025 pm 03:33 PM

부트 스트랩을 사용하여 검색 표시 줄의 값을 얻는 방법 : 검색 표시 줄의 ID 또는 이름을 결정하십시오. JavaScript를 사용하여 DOM 요소를 얻으십시오. 요소의 값을 가져옵니다. 필요한 작업을 수행하십시오.

부트 스트랩 날짜를 확인하는 방법 부트 스트랩 날짜를 확인하는 방법 Apr 07, 2025 pm 03:06 PM

부트 스트랩의 날짜를 확인하려면 다음 단계를 따르십시오. 필요한 스크립트와 스타일을 소개하십시오. 날짜 선택기 구성 요소를 초기화합니다. 검증을 활성화하려면 데이터 BV 날짜 속성을 설정합니다. 검증 규칙 (예 : 날짜 형식, 오류 메시지 등) 구성; 부트 스트랩 검증 프레임 워크를 통합하고 양식이 제출 된 경우 날짜 입력을 자동으로 확인하십시오.

부트 스트랩에 분할 라인을 작성하는 방법 부트 스트랩에 분할 라인을 작성하는 방법 Apr 07, 2025 pm 03:12 PM

부트 스트랩 분할 라인을 만드는 두 가지 방법이 있습니다 : 태그를 사용하여 수평 분할 라인이 생성됩니다. CSS 테두리 속성을 사용하여 사용자 정의 스타일 분할 라인을 만듭니다.

See all articles