• SSM+BootStrap增删改查,以及头像上传


    先看界面

    点击编辑之后

    具体代码请往下看

    一、jsp界面

      1 <%@ page language="java" contentType="text/html; charset=UTF-8"
      2     pageEncoding="UTF-8"%>
      3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
      4 <html>
      5 <head>
      6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      7 <title>Insert title here</title>
      8 </head>
      9 <link
     10     href="${pageContext.request.contextPath }/bootstrap-3.3.7-dist/css/bootstrap.css"
     11     rel="stylesheet"></link>
     12 <link
     13     href="${pageContext.request.contextPath }/bootstrap-fileinput/css/fileinput.css"
     14     media="all" rel="stylesheet" type="text/css" />
     15 <link
     16     href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
     17     media="all" rel="stylesheet" type="text/css" />
     18 <link
     19     href="${pageContext.request.contextPath }/bootstrap-fileinput/themes/explorer-fa/theme.css"
     20     media="all" rel="stylesheet" type="text/css" />
     21 <link
     22     href="${pageContext.request.contextPath }/bootstrap-table-develop/docs/dist/bootstrap-table.css"
     23     rel="stylesheet"></link>
     24 <script
     25     src="${pageContext.request.contextPath }/bootstrap-3.3.7-dist/js/jquery.js"></script>
     26 <script
     27     src="${pageContext.request.contextPath }/bootstrap-fileinput/js/plugins/sortable.js"
     28     type="text/javascript"></script>
     29 <script
     30     src="${pageContext.request.contextPath }/bootstrap-fileinput/js/fileinput.js"
     31     type="text/javascript"></script>
     32 <script
     33     src="${pageContext.request.contextPath }/bootstrap-fileinput/js/locales/fr.js"
     34     type="text/javascript"></script>
     35 <script
     36     src="${pageContext.request.contextPath }/bootstrap-fileinput/js/locales/es.js"
     37     type="text/javascript"></script>
     38 <script
     39     src="${pageContext.request.contextPath }/bootstrap-fileinput/themes/explorer-fa/theme.js"
     40     type="text/javascript"></script>
     41 <script
     42     src="${pageContext.request.contextPath }/bootstrap-fileinput/themes/fa/theme.js"
     43     type="text/javascript"></script>
     44 <script
     45     src="${pageContext.request.contextPath }/bootstrap-fileinput/js/locales/zh.js"></script>
     46 <script
     47     src="${pageContext.request.contextPath }/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
     48 <script
     49     src="${pageContext.request.contextPath }/bootstrap-table-develop/docs/dist/bootstrap-table.js"></script>
     50 <script
     51     src="${pageContext.request.contextPath }/bootstrap-table-develop/docs/dist/js/bootstrap-table-locale-all.js"></script>
     52 <script
     53     src="${pageContext.request.contextPath }/bootstrap-table-develop/src/locale/bootstrap-table-zh-CN.js"></script>
     54 <body>
     55     <table id="result" class="table table-hover"
     56         style="text-align: center;">
     57         <thead style="text-align: center;">
     58             <th data-field="stuid">学生编号</th>
     59             <th data-field="stuname">学生姓名</th>
     60             <th data-field="classes.classname">班级名称</th>
     61             <th data-field="userimage" data-formatter="image">头像</th>
     62             <th data-field="state" data-formatter="state">状态</th>
     63             <th data-field="caozuo" data-formatter="toolbar">操作</th>
     64         </thead>
     65     </table>
     66     <form action="#" id="formid" onsubmit="return false"
     67         enctype="multipart/form-data">
     68         <div class="modal fade" id="myModal" tabindex="-1" role="dialog"
     69             aria-labelledby="myModalLabel" aria-hidden="true">
     70             <div class="modal-dialog">
     71                 <div class="modal-content">
     72                     <div class="modal-header">
     73                         <button type="button" class="close" data-dismiss="modal"
     74                             aria-hidden="true">&times;</button>
     75                         <h4 class="modal-title" id="myModalLabel">学生信息修改</h4>
     76                     </div>
     77                     <div class="modal-body">
     78                         学生编号:<input type="text" name="stuid" class="form-control" value=""
     79                             readonly="readonly" /><br> 学生姓名:<input type="text"
     80                             name="stuname" class="form-control" id="stuname" value=""><br>
     81                         所在班级:<select id="class" name="classesid" class="form-control">
     82                         </select> 当前头像:
     83                         <div>
     84                             <img alt="" style=" 40px; height: 40px" id="img">
     85                         </div>
     86                         用户头像:
     87                         <div class="file-loading">
     88                             <input id="file-fr" name="file" type="file" multiple>
     89                         </div>
     90 
     91                         <input type="hidden" id="userimage" name="userimage" value="" />
     92                     </div>
     93                     <div class="modal-footer">
     94                         <button type="button" onclick="update()" class="btn btn-primary"
     95                             data-dismiss="modal">提交更改</button>
     96                         <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
     97                     </div>
     98                 </div>
     99                 <!-- /.modal-content -->
    100             </div>
    101             <!-- /.modal -->
    102         </div>
    103     </form>
    104 </body>
    105 <script>
    106     $('#file-fr').fileinput({
    107         theme : 'fa',
    108         language : 'zh',
    109         uploadAsync : true,//异步上传
    110         uploadUrl : 'upload.do',
    111         allowedFileExtensions : [ 'jpg', 'png', 'gif', 'mp4' ],
    112         maxFileSize : 0,
    113         maxFileCount : 1
    114     }).on("fileuploaded", function(event, data) { //异步上传成功结果处理
    115         $("#userimage").val(data.response.src);
    116     })
    117 </script>
    118 <script type="text/javascript">
    119     $(function() {
    120         $("#result").bootstrapTable({
    121             url : "selectAll.do",
    122             method : "post",
    123             cache : false,
    124             dataType : "json",
    125             contentType : "application/x-www-form-urlencoded",//post的方式提交的话需要写
    126             toolbar : "#toolbar",
    127             toolbarAlign : "left",
    128             striped : true,
    129             pagination : true,
    130             sidePagination : "server",
    131             pageNumber : 1,
    132             pageSize : 5,
    133             pageList : [ 5, 10, 15 ],
    134             locale : "zh-CN",
    135             queryParamsType : "limit",
    136             queryParams : queryParams
    137         });
    138     });
    139 
    140     function queryParams(params) {
    141         var params = {
    142             pageSize : params.limit,
    143             pageCode : params.offset / params.limit + 1
    144         };
    145         return params;
    146     };
    147     function state(value, row, index) {
    148         if (row['state'] === 0) {
    149             return "正常";
    150         }
    151         if (row['state'] === 1) {
    152             return "锁定";
    153         }
    154         return value;
    155     }
    156     function image(value, row, index) {
    157         return "<img src='"+row['userimage']+"' style='30px;height:30px;'/>";
    158     }
    159     /*操作按钮*/
    160     function toolbar(value, row, index) {
    161         var element = "<button type='button' onclick='edit(" + row.stuid
    162                 + ")' class='btn btn-info'>编辑</button>"
    163                 + "<button type='button' onclick='del(" + row.stuid
    164                 + ")' class='btn btn-danger'>删除</button>"
    165                 + "<button type='button' onclick='download(" + row.stuid
    166                 + ")' class='btn btn-warning'>下载</button>";
    167         return element;
    168     }
    169     /*编辑按钮,弹出模态框*/
    170     function edit(stuid) {
    171         $("#class option").remove();
    172         $("#formid")[0].reset();
    173         $.ajax({
    174             url : "editBystuid.do?stuid=" + stuid,
    175             type : "post",
    176             dataType : "json",
    177             success : function(data) {
    178                 $('#myModal').modal('show');
    179                 $("[name=stuid]").val(data[0].stuid);
    180                 $("#stuname").val(data[0].stuname);
    181                 $("#userimage").val(data[0].userimage);
    182                 $("#img").attr('src', data[0].userimage);
    183                 $("#class").append(
    184                         "<option value='"+data[0].calssesid+"'>"
    185                                 + data[0].classes.classname + "</option>");
    186             }
    187         });
    188         $.ajax({
    189             url : "selectAllClass.do",
    190             type : "post",
    191             dataType : "json",
    192             success : function(data) {
    193                 var obj = $("#class");
    194                 for (var i = 0; i < data.length; i++) {
    195                     var op = "<option value='"+data[i].classesid+"'>"
    196                             + data[i].classname + "</option>";
    197                     obj.append(op);
    198                 }
    199             }
    200         })
    201     };
    202     /*修改操作*/
    203     function update() {
    204         $.ajax({
    205             url : "updateBystuid.do",
    206             type : "get",
    207             dataType : "text",
    208             data : $("#formid").serialize(),
    209             success : function(data) {
    210                 if (data == "ok") {
    211                     $("#result").bootstrapTable("refresh", {
    212                         url : "selectAll.do"
    213                     });
    214                 } else if (data == "error") {
    215                     alert("修改失败!");
    216                 }
    217             }
    218         });
    219 
    220     }
    221     /*删除操作*/
    222     function del(stuid) {
    223         if (confirm('确定要删除吗?') == true) {
    224             $.ajax({
    225                 url : "delBystuid.do?stuid=" + stuid,
    226                 type : "post",
    227                 dataType : "text",
    228                 success : function(data) {
    229                     if (data == "ok") {
    230                         $("#result").bootstrapTable("refresh", {
    231                             url : "selectAll.do"
    232                         });
    233                     } else if (data == "error") {
    234                         alert("删除失败");
    235                     }
    236                 }
    237             })
    238             return false;
    239         }
    240     }
    241     /*下载*/
    242     function download(stuid){
    243         if(confirm('确定要下载头像?')==true){
    244             location.href="download.do?stuid="+stuid;
    245             /* $.ajax({
    246                 url:"download.do?stuid="+stuid,
    247                 type:"post",
    248                 dataType:"json",
    249                 success:function(data){
    250                     
    251                 }
    252             }); */
    253         }
    254     }
    255 </script>
    256 </html>

    二、Controller层代码

      1 package com.llh.controller;
      2 
      3 import java.io.File;
      4 import java.io.IOException;
      5 import java.util.Date;
      6 import java.util.List;
      7 import java.util.Random;
      8 
      9 import javax.annotation.Resource;
     10 import javax.servlet.http.HttpServletRequest;
     11 
     12 import org.apache.commons.io.FileUtils;
     13 import org.springframework.context.annotation.Scope;
     14 import org.springframework.http.HttpHeaders;
     15 import org.springframework.http.HttpStatus;
     16 import org.springframework.http.MediaType;
     17 import org.springframework.http.ResponseEntity;
     18 import org.springframework.stereotype.Controller;
     19 import org.springframework.web.bind.annotation.ModelAttribute;
     20 import org.springframework.web.bind.annotation.RequestMapping;
     21 import org.springframework.web.bind.annotation.ResponseBody;
     22 import org.springframework.web.multipart.MultipartFile;
     23 
     24 import com.github.pagehelper.PageHelper;
     25 import com.github.pagehelper.PageInfo;
     26 import com.llh.entity.Student;
     27 import com.llh.service.StudentService;
     28 
     29 import net.sf.json.JSONArray;
     30 
     31 @Controller
     32 @Scope("prototype")
     33 public class StudentController {
     34 
     35     @Resource
     36     private StudentService studentService;
     37 
     38     /**
     39      * 分页查询所有
     40      * 
     41      * @param pageCode
     42      * @param pageSize
     43      * @return
     44      */
     45     @RequestMapping(value = "selectAll", produces = "text/html;charset=utf-8")
     46     public @ResponseBody String selectAll(int pageCode, int pageSize) {
     47         PageHelper.startPage(pageCode, pageSize);
     48         List<Student> slist = studentService.selectAll();
     49         PageInfo<Student> spi = new PageInfo<Student>(slist);
     50         int count = (int) spi.getTotal();
     51         JSONArray json = JSONArray.fromObject(slist);
     52         String str = "{"total":" + count + ","rows":" + json.toString() + "}";
     53         return str;
     54     }
     55 
     56     /**
     57      * 上传
     58      * 
     59      * @param request
     60      * @param file
     61      * @return
     62      * @throws IllegalStateException
     63      * @throws IOException
     64      */
     65     @RequestMapping(value = "upload")
     66     public @ResponseBody String upload(HttpServletRequest request, MultipartFile file)
     67             throws IllegalStateException, IOException {
     68         String name = file.getOriginalFilename();
     69         String path = request.getServletContext().getRealPath("/upload/");// 上传保存的路径
     70         String fileName = changeName(name);
     71         String rappendix = "upload/" + fileName;
     72         fileName = path + "\" + fileName;
     73         File file1 = new File(fileName);
     74         file.transferTo(file1);
     75         String str = "{"src":"" + rappendix + ""}";
     76         return str;
     77     }
     78 
     79     public static String changeName(String oldName) {
     80         Random r = new Random();
     81         Date d = new Date();
     82         String newName = oldName.substring(oldName.indexOf('.'));
     83         newName = r.nextInt(99999999) + d.getTime() + newName;
     84         return newName;
     85     }
     86 
     87     /**
     88      * 编辑
     89      * 
     90      * @param stuid
     91      * @param session
     92      * @return
     93      */
     94     @RequestMapping(value = "editBystuid", produces = "text/html;charset=utf-8")
     95     public @ResponseBody String editBystuid(Integer stuid) {
     96         System.out.println("编辑");
     97         Student s = studentService.selectByPrimaryKey(stuid);
     98         JSONArray json = JSONArray.fromObject(s);
     99         String js = json.toString();
    100         System.out.println(js);
    101         return js;
    102     }
    103 
    104     /**
    105      * 修改
    106      * 
    107      * @param stuid
    108      * @param stuname
    109      * @return
    110      */
    111     @RequestMapping(value = "updateBystuid", produces = "text/html;charset=utf-8")
    112     public @ResponseBody String updateBystuid(@ModelAttribute Student s) {
    113         System.out.println("修改中");
    114         System.out.println(s.getStuname() + s.getStuid()+s.getUserimage());
    115         int a = studentService.updateByPrimaryKey(s);
    116         if (a != 0) {
    117             return "ok";
    118         }
    119         return "error";
    120     }
    121 
    122     /**
    123      * 下载
    124      * 
    125      * @param stuid
    126      * @return
    127      * @throws IOException 
    128      */
    129     @RequestMapping(value = "download", produces = "text/html;charset=utf-8")
    130     public ResponseEntity<byte[]> download(Integer stuid,HttpServletRequest request) throws IOException {
    131         Student s = studentService.selectByPrimaryKey(stuid);
    132         String path=request.getServletContext().getRealPath("\");
    133         String downpath = path+s.getUserimage();
    134         File file1=new File(downpath);
    135         //String downloadFileName=new String(downpath.getBytes("UTF-8"),"iso-8859-1");
    136         HttpHeaders heads=new HttpHeaders();
    137         heads.setContentDispositionFormData("attachment", downpath);
    138         heads.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    139         return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file1), heads,HttpStatus.CREATED);
    140     }
    141     
    142     
    143 
    144 }

    三、dao层和service层实体类就掠过了

    这里使用到的有自动生成实体类,Maven的分页

    具体操作请看首页

  • 相关阅读:
    Maven pom.xml中的元素modules、parent、properties以及import
    WebService与RMI(远程调用方式实现系统间通信)
    负载均衡+session共享(memcached-session-manager实现)
    LVS + keepalived + nginx + tomcat 实现主从热备 + 负载均衡
    将tomcat添加为linux系统服务
    virtualBox安装centos,并搭建tomcat
    主从热备+负载均衡(LVS + keepalived)
    利用maven/eclipse搭建ssm(spring+spring mvc+mybatis)
    排序之归并排序
    排序之快速排序(下)
  • 原文地址:https://www.cnblogs.com/javallh/p/8289032.html
Copyright © 2020-2023  润新知