实用功能汇总

实用功能汇总

1.上传文件(图片)

controller

package com.example.admin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/file_test")

public class File_uploadtTest {
    @RequestMapping("/add")
    @ResponseBody
    public String addUser(HttpServletRequest request, HttpServletResponse response,
                          MultipartFile file) throws IOException {

        String fileName = file.getOriginalFilename();//获取文件名
        System.out.println("获取文件名"+fileName);
        fileName = getFileName(fileName);          //添加时间戳后的文件名
        System.out.println("获取文件名加时间"+fileName);
        request.getSession().setAttribute("fileImgName",fileName);
        String filepath = getUploadPath();     //获取当前系统路径
        if (!file.isEmpty()) {                  //如果文件不为空
            try (BufferedOutputStream out = new BufferedOutputStream(   //上传
                    new FileOutputStream(new File(filepath + File.separator + fileName)))) {
                out.write(file.getBytes());
                out.flush();
            } catch (FileNotFoundException e) {
                System.out.println("上传文件失败 FileNotFoundException:" + e.getMessage());
            } catch (IOException e) {
                System.out.println("上传文件失败 IOException:" + e.getMessage());
            }

        } else {
            System.out.println("上传文件失败,文件为空");
        }
        return "ok";
    }
    
    /**
     * 文件名后缀前添加一个时间戳
     */
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
        String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }

    /**
     * 获取当前系统路径
     */
    private String getUploadPath() {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) path = new File("");
        File upload = new File(path.getAbsolutePath(), "src/main/resources/static/img/");
        if (!upload.exists()) upload.mkdirs();
        return upload.getAbsolutePath();
    }

}

html页面

  <div class="x-body">

            <form action="file_test/add" method="post" enctype="multipart/form-data">

                <input type="file" id="file" name="file" /> <br />

                <div class="layui-form-item">
                    <button  class="layui-btn" lay-filter="add" >
                        上传
                    </button>
                </div>

            </form>

        </div>

注意:

image-20220327173500836

2.layui页面的添加之后自动关闭并且刷新

点击确认 添加成功 就自动关闭 并且刷新数据

image-20220327174042673

 function add_art() {
      var lid=$("#lid").val();
      var art_title=$("#art_title").val();
      var art_content=$("#art_content").val();
      $.ajax({
        url:"article/add",
        data:{"lid":lid,"title":art_title,"content":art_content},
        dataType:"json",
        type:"post",
        success:function (data) {
          if(data>0){
            alert("添加成功");
            //location.href="javascript:location.replace(location.href)";(这个是 刷新当前页面)
            // 获得frame索引
            var index = parent.layer.getFrameIndex(window.name);
            //关闭当前frame
            parent.layer.close(index);
            window.parent.location.reload();

          }else {
            alert("添加失败");
          }
        },
        error:function (data) {
          alert("后台没传数据");
        }
      })
    }

3.标签select 通过后台拿到数据显示到option中

<div class="layui-input-inline">
          <select name="article" id="lid" class="lable" lay-filter="scienceid" lay-verify="required" >
            <option value="0">请选择标签</option>
          </select>
        </div>


 <script>
    var form;
    layui.use(['form', 'layer'], function () {
      $ = layui.jquery;
     form = layui.form()
              , layer = layui.layer;
      //写在form验证之前才可以显示出来
        $.ajax({
          url:"admin_lable/selectall",
          dataType:"json",
          type:"post",
          success:function (data) {
            for (var i = 0; i <data.length ; i++) {
              $("#lid").append("<option value='"+data[i].id+"'>"+data[i].lname+"</option>");
            }
            form.render();
          },
          error:function (data) {
            alert("后台没传数据");
          }
        })
    });
  </script>

4.修改(ajax在两个页面中)

注意:需要写两个ajax发送请求 拿到数据 在写一个ajax将数据显示到 update.html的页面上

list的显示条数的页面上 点击查询

image-20220327175038900

image-20220327175344531

在update页面上来就加载 后台存的session的值

image-20220327175439210

image-20220327175636354

5.ajax+mybatis实现分页查询+模糊查询+多条件查询

实现的效果

image-20220327180032040

前台js

<script>
function sreach(page) {
    var seach_title=$("#seach_title").val();
    var seach_lname=$("#seach_lname").val();
    $.ajax({
        url:"article/mh",
        data:{"page":page,"seach_title":seach_title,"seach_lname":seach_lname},
        type:"post",
        dataType:"json",
        success:function (data) {
            $("#sumCount").html(data.count);//总条数打印到页面上
            var h="";
            for (var i = 0; i <data.list.length ; i++) {
                h+="<tr>\n" +
                    "<td><input type=\"checkbox\" value=\"1\" name=\"\"></td>\n" +
                    "<td>"+data.list[i].id+"</td>\n" +
                    "<td>"+data.list[i].uname+"</td>\n" +
                    "<td>"+data.list[i].title+"</td>\n" +
                    "<td>"+data.list[i].lname+"</td>\n" +
                    "<td>"+data.list[i].content+"</td>\n" +
                    "<td>"+data.list[i].heat+"</td>\n" +
                    "<td>"+data.list[i].createtime+"</td>\n" +
                    "<td class=\"td-manage\">\n" +
                    "<a style=\"text-decoration:none\"\n" +
                    "οnclick=\"member_password('修改用户','article-update.html','1001','600','400',sendOne('"+data.list[i].id+"'))\" href=\"javascript:;\"\n" +
                    "                            title=\"修改用户\">\n" +
                    "                            <i class=\"layui-icon\">&#xe631;</i>\n" +
                    "                        </a>\n" +
                    "                        <a title=\"删除\" href=\"javascript:;\" οnclick=\"member_del(this,'"+data.list[i].id+"')\" style=\"text-decoration:none\">\n" +
                    "                            <i class=\"layui-icon\">&#xe640;</i>\n" +
                    "                        </a>\n" +
                    "                    </td>\n" +
                    "                </tr>";
            }
                    $("#selectall").html(h);

                    //动态非配分页
                    var s=data.page-1>0?data.page-1:1;
                    var x=data.page+1>data.sumpage?data.sumpage:data.page+1;
                    var f=  '<a href="javascript:void(0)" οnclick="sreach(1)">首页</a>'+
                        '<a href="javascript:void(0)" οnclick="sreach('+s+')">上一页</a>'+
                        '<a href="javascript:void(0)" οnclick="sreach('+x+')">下一页</a>'+
                        '<a href="javascript:void(0)" οnclick="sreach('+data.sumpage+')">末页</a>'+
                        '<span>当前页/总页:'+data.page+'/'+data.sumpage+'</span>'+
                        '<input id="gos" style="width:30px">'+
                        '<input type="button" οnclick="gos()" value="GO">';
                    $("#fy").html(f);
                },
                error:function (data) {
                    alert("error");
                }
            })
        }
    
</script>

controller层

@RequestMapping("/mh")
    @ResponseBody
    public String mh(HttpServletRequest request){ //模糊查询+分页+关联
        String page=request.getParameter("page");
        if(page==null || "".equals(page)){
            page="1";
        }
        String seach_title=request.getParameter("seach_title");//搜索标题
        String seach_lname=request.getParameter("seach_lname");//搜索标签
        User user = (User) request.getSession().getAttribute("user");
        //页面传来的值 存在condition对象中
        condition condition=new condition();
        condition.setPage(Integer.parseInt(page));
        condition.setSeach_title(seach_title);
        condition.setSeach_lname(seach_lname);
        condition.setUid(user.getId());

        List<Map<String,Object>> list = articleService.mh(condition);//模糊查询+分页+关联
        //模糊查询总条数
        List<Map<String, Object>> count2 = articleService.count2(condition);
        int sum = count2.size();//总条数
        int sumpage=sum%4>0?(sum/4+1):(sum/4);//页面的总页数
        //将从后台查询到的值封装在dgb对象中
        datagridebean dgb=new datagridebean();
        dgb.setList(list);
        dgb.setCount(sum);
        dgb.setPage(Integer.parseInt(page));//当前页
        dgb.setSumpage(sumpage);
        //将数据转为json格式 给页面
        String json = JSON.toJSONStringWithDateFormat(dgb, "yyyy-MM-dd");
        return json;
    }

service的impl

  @Override
    public List<Map<String, Object>> mh(condition condition) {
        int page = condition.getPage();
        int f=(page-1)*4;
        condition.setPage(f);
        return adminlableMapper.mh(condition);
    }

mapper.xml

 <select id="mh" parameterType="com.example.admin.entity.condition" resultType="Map" >
        select art.*,u.uname,la.lname
        from article art,user u,lable la
        where art.uid=u.id and art.lid=la.id and title like '%${seach_title}%'
        and lname like '%${seach_lname}%' and u.id=#{uid}
        ORDER BY id limit #{page},4
    </select>

    <select id="count2" parameterType="com.example.admin.entity.condition" resultType="Map" >
        select art.*,u.uname,la.lname
        from article art,user u,lable la
        where art.uid=u.id and art.lid=la.id and title like '%${seach_title}%'
        and lname like '%${seach_lname}%' and u.id=#{uid}
    </select>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值