検索
ホームページウェブフロントエンドブートストラップのチュートリアルSSM+BootStrap を使用して追加、削除、変更、確認、アバターのアップロードの効果を実現する方法についての簡単な説明

本篇文章给大家通过示例介绍一下使用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 id="学生信息修改">学生信息修改</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="max-width:90%" 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;/ alt="SSM+BootStrap を使用して追加、削除、変更、確認、アバターのアップロードの効果を実現する方法についての簡単な説明" >";
    }
    /*操作按钮*/
    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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事は博客园で複製されています。侵害がある場合は、admin@php.cn までご連絡ください。
Bootstrapの目的:一貫した魅力的なWebサイトの構築Bootstrapの目的:一貫した魅力的なWebサイトの構築Apr 19, 2025 am 12:07 AM

Bootstrapの主な目的は、開発者がレスポンシブでモバイルファーストのWebサイトを迅速に構築できるようにすることです。そのコア関数には、次のものが含まれます。1。グリッドシステムを介したさまざまなデバイスのレイアウト調整を実現するレスポンシブ設計。 2。ナビゲーションバーやモーダルボックスなどの事前定義されたコンポーネントは、美学とクロスブラウザーの互換性を確保します。 3.カスタマイズと拡張機能をサポートし、SASS変数とミックスインを使用してスタイルを調整します。

Bootstrap vs.その他のフレームワーク:比較概要Bootstrap vs.その他のフレームワーク:比較概要Apr 18, 2025 am 12:06 AM

Bootstrapは、使いやすく、レスポンシブWebサイトをすばやく開発できるため、Tailwindcss、Foundation、およびBulmaよりも優れています。 1.BootStrapは、事前に定義されたスタイルとコンポーネントの豊富なライブラリを提供します。 2。そのCSSおよびJavaScriptライブラリは、レスポンシブデザインとインタラクティブな機能をサポートしています。 3.迅速な発展に適していますが、カスタムスタイルはより複雑になる場合があります。

Reactのブートストラップスタイルの統合:方法とテクニックReactのブートストラップスタイルの統合:方法とテクニックApr 17, 2025 am 12:04 AM

Reactプロジェクトにブートストラップを統合することは、2つの方法で行うことができます。1)小規模プロジェクトまたは迅速なプロトタイピングに適したCDNを使用して導入します。 2)NPMパッケージマネージャーを使用したインストール。深いカスタマイズが必要なシナリオに適しています。これらの方法を使用すると、Reactで美しく応答性の高いユーザーインターフェイスをすばやく構築できます。

Reactのブートストラップ:利点とベストプラクティスReactのブートストラップ:利点とベストプラクティスApr 16, 2025 am 12:17 AM

BootstrapをReactプロジェクトに統合することの利点には、1)迅速な開発、2)一貫性と保守性、および3)レスポンシブデザインが含まれます。 CSSファイルを直接導入するか、React-Bootstrapライブラリを使用することにより、ReactプロジェクトでBootstrapのコンポーネントとスタイルを効率的に使用できます。

ブートストラップ:Webフレームワークのクイックガイドブートストラップ:WebフレームワークのクイックガイドApr 15, 2025 am 12:10 AM

Bootstrapは、Twitterが開発したフレームワークであり、レスポンシブでモバイルファーストのWebサイトとアプリケーションを迅速に構築できます。 1.使いやすさとリッチなコンポーネントライブラリにより、開発が速くなります。 2。巨大なコミュニティは、サポートとソリューションを提供します。 3.レスポンシブグリッドの作成など、CDNを介してスタイルを制御するためにクラス名を紹介および使用します。 4。カスタマイズ可能なスタイルと拡張コンポーネント。 5.利点には、迅速な開発とレスポンシブデザインが含まれますが、欠点はスタイルの一貫性と学習曲線です。

ブートストラップの分解:それが何であり、なぜそれが重要なのかブートストラップの分解:それが何であり、なぜそれが重要なのかApr 14, 2025 am 12:05 AM

bootstrapisafree、open-sourcessframeworkthatsthatssponsiveandmobile-firstwebitedevelopment。

ブートストラップ:Webデザインを簡単にしますブートストラップ:Webデザインを簡単にしますApr 13, 2025 am 12:10 AM

Webデザインがブートストラップを簡単にするものは何ですか?そのプリセットコンポーネント、レスポンシブデザイン、豊富なコミュニティサポート。 1)プリセットコンポーネントライブラリとスタイルにより、開発者は複雑なCSSコードの作成を避けることができます。 2)ビルトイングリッドシステムは、レスポンシブレイアウトの作成を簡素化します。 3)コミュニティサポートは、豊富なリソースとソリューションを提供します。

Bootstrapの影響:Web開発の加速Bootstrapの影響:Web開発の加速Apr 12, 2025 am 12:05 AM

BootstrapはWeb開発を加速し、事前に定義されたスタイルとコンポーネントを提供することにより、開発者は迅速にレスポンシブWebサイトを構築できます。 1)プロジェクトの数日以内に基本的なレイアウトを完了するなど、開発時間を短縮します。 2)SASS変数とミキシンを通じて、ブートストラップにより、カスタムスタイルが特定のニーズを満たすことができます。 3)CDNバージョンを使用すると、パフォーマンスを最適化し、負荷速度を向上させることができます。

See all articles

ホット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ヘンタイを無料で生成します。

ホットツール

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター