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> $('#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) { //异步上传成功结果处理 $("#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;'/ alt="SSM+BootStrap을 사용하여 추가, 삭제, 수정, 확인 및 아바타 업로드 효과를 얻는 방법에 대한 간략한 설명" >"; } /*操作按钮*/ 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; } /*编辑按钮,弹出模态框*/ 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("修改失败!"); } } }); } /*删除操作*/ 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을 사용하여 추가, 삭제, 수정, 확인 및 아바타 업로드 효과를 얻는 방법에 대한 간략한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

부트 스트랩을 React 프로젝트에 통합하는 단계에는 다음이 포함됩니다. 1. 부트 스트랩 패키지 설치, 2. CSS 파일 가져 오기, 3. 부트 스트랩 클래스 이름을 스타일 요소에 사용하십시오. 이 통합은 REACT의 구성 요소화 및 부트 스트랩의 스타일 시스템을 사용하여 효율적인 UI 개발을 달성합니다.

BootStrapisApowerfulframeworkstimplifiescreatingresponsive, mobile-firstwebsites.itoffers : 1) Agridsystemforadaptablelayouts, 2) pre-styledements-buttonsandforms 및 3) javascromponentssuchascarouselsforenhancedinteractifice.

Bootstrap은 Twitter에서 개발 한 프론트 엔드 프레임 워크로 HTML, CSS 및 JavaScript를 통합하여 개발자가 반응 형 웹 사이트를 신속하게 구축 할 수 있도록 도와줍니다. 핵심 기능에는 다음이 포함됩니다. 그리드 시스템 및 레이아웃 : 12 열 설계, Flexbox 레이아웃 사용 및 다양한 장치 크기의 반응 형 페이지를 지원하는 것이 포함됩니다. 구성 요소 및 스타일 : 버튼, 모달 박스 등과 같은 풍부한 구성 요소 라이브러리를 제공하며 클래스 이름을 추가하여 아름다운 효과를 얻을 수 있습니다. 작동 방식 : CSS 및 JavaScript에 의존하면 CSS는 적은 또는 SASS 전 처리기를 사용하며 JavaScript는 jQuery를 사용하여 대화식 및 동적 효과를 달성합니다. 이러한 기능을 통해 부트 스트랩은 개발을 크게 향상시킵니다

bootstrapisafreecssframework that thatwebdevelopmentbyprovingpre-styledcomponentsandjavascriptplugins.it'sidealforcreatingresponsive, mobile-firstwebsites, powerfilectiblegridsystemforlayoutSandasupportiveCommunityOrlynityAndOcustomization.

BootstrapisAfree, Open-SourcecsSframeworkthathelpScreateResponsive, mobile-firstwebsites.1) itofferSagridsystemforlayoutFlexibility, 2) incespre-styledcomponentsforquickDesign 및 3) ishighlyCustomaMaSavoidGenericLooks, ButRequirsTOTET

부트 스트랩은 빠른 건설 및 소규모 프로젝트에 적합하지만 React는 복잡하고 대화식 응용 프로그램에 적합합니다. 1) Bootstrap은 사전 정의 된 CSS 및 JavaScript 구성 요소를 제공하여 반응 형 인터페이스 개발을 단순화합니다. 2) React는 구성 요소 개발 및 가상 DOM을 통해 성능과 상호 작용을 향상시킵니다.

Bootstrap의 주요 목적은 개발자가 반응 형 모바일 우선 웹 사이트를 신속하게 구축 할 수 있도록 돕는 것입니다. 핵심 기능에는 다음이 포함됩니다. 1. 반응 형 디자인은 그리드 시스템을 통한 다양한 장치의 레이아웃 조정을 실현합니다. 2. 내비게이션 바 및 모달 박스와 같은 사전 정의 된 구성 요소는 미학 및 크로스 브라우저 호환성을 보장합니다. 3. 사용자 정의 및 확장을 지원하고 SASS 변수 및 Mixins를 사용하여 스타일을 조정하십시오.

Bootstrap은 사용하기 쉽고 반응 형 웹 사이트를 신속하게 개발하기 쉽기 때문에 Tailwindcss, Foundation 및 Bulma보다 낫습니다. 1. Bootstrap은 미리 정의 된 스타일과 구성 요소의 풍부한 라이브러리를 제공합니다. 2. CSS 및 JavaScript 라이브러리는 반응 형 디자인 및 대화식 기능을 지원합니다. 3. 빠른 개발에 적합하지만 맞춤형 스타일이 더 복잡 할 수 있습니다.


핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

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

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경
