常见的SPRINGMVC问题(1)

本文深入探讨了SpringMVC框架中@RequestParam注解的使用方法,包括必填与非必填参数处理、默认值设定、前端时间显示、JSON数据交互、文件上传与下载等关键功能,提供了丰富的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

致谢:这篇博客写于我毕设答辩之后,毕设是MOOC学习平台设计实现。小本科生一枚,本科西安读的,希望老师给我过。感谢这所大学所有计算机学院老师给我的教导,感谢我的舍友四年来不杀之恩·

@RequestParam

@RequestParam(name = “teacherId” ,required = true) int teacherId

默认为true ,name表示前端传过来的字段。required表示必须有,没有的话就是下边的错误

{"timestamp":"2019-05-04T13:56:02.990+0000","status":400,"error":"Bad Request","message":"Required int parameter 'xx' is not present","trace":"org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'xx' is not present\r\n\tat org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:202)\r\n\tat org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:113)\r\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:126)\r\n\tat 

如果是@RequestParam(name=“xx”,required = false) int tt

web报错500

POSTMAN测试结果
 "timestamp": "2019-05-10T04:04:07.982+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "Optional int parameter 'xx' is present but cannot be translated into a null value due to being declared as a primitive type. 
报错(int型必须要有默认值吧)
java.lang.IllegalStateException: Optional int parameter 'xx' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.

解决办法:

你可以给个默认的值,defaultValue =“11” ,也可以使用String接受后转为int即可。或者使用Integer来接受不会报错。没有赋值的Integer和String为null;如果是没有该key的值,类似请求就是http://localhost:8080/test?xx=则会认为是null,无论是Integer还是String,int会400错误

如果给个默认值,只能是String类型

@RequestParam(name="xx",required = false,defaultValue = "11") String tt

这个不会报错

如果给默认值

@RequestParam(name="xx",required = false,defaultValue = "0") int tt

不会报错

前端的时间显示问题(后台传前台直接显示)

如果直接传过去

<span th:text="${course.courseCreateDate}"></span>
效果

在这里插入图片描述
我这里使用了thymeleaf模板引擎

 <span th:text="${#dates.format(course.courseCreateDate)}"></span>

效果
在这里插入图片描述
带上格式参数

<span th:text="${#dates.format(course.courseCreateDate,'yyyy-MM-dd HH:mm')}"></span>

在这里插入图片描述

对后台Json串的认识

测试代码

 List<CourseSelection> courseSelections;

        if(userId > 0){
            log.warn("查看选课星系"+ userId);
             courseSelections =courseSelectionService.selectCourseByUserId(userId);
        }else
            courseSelections=  courseSelectionService.selectCourseByUserId(0);
        Map map = new HashMap();
        Map map1 = new HashMap();
        map1.put("name","maqiang");
        map1.put("sex","男");
        // map对象
        map.put("map",map1);
//Java对象
        User a = new User();
        a.setUserType(2);
        a.setUserId(23);
        a.setUserName("马");
        map.put("Object" ,a);
//List<Object>
        map.put("data",courseSelections);
        map.put("code",0);
        map.put("msg",11);
        map.put("count",courseSelections.size());
        return map;
    }

结果

{
  "msg": 11,
  "code": 0,
  "data": [
    {
      "courseSelectionId": 1,
      "userId": 1,
      "courseId": 1,
      "process": 1,
      "grade": 0,
      "courseName": "C"
    },
    {
      "courseSelectionId": 2,
      "userId": 0,
      "courseId": 1,
      "process": 0,
      "grade": 0,
      "courseName": "C"
    },
    {
      "courseSelectionId": 3,
      "userId": 0,
      "courseId": 5,
      "process": 0,
      "grade": 0,
      "courseName": "Java"
    },
    {
      "courseSelectionId": 4,
      "userId": 22,
      "courseId": 10,
      "process": 0,
      "grade": 0,
      "courseName": "dfasdf"
    }
  ],
  "count": 4,
  "Object": {
    "userId": 23,
    "userName": "马",
    "userPassword": null,
    "userTel": null,
    "userType": 2
  },
  "map": {
    "sex": "男",
    "name": "maqiang"
  }
}

返回List

我这里需要使用百度e-charts的绘图插件

    @RequestMapping("/admin/adminechartsadminPage")
    public String gotoAdmineCharsPage(){
        return "sum/adminschool";
    }
    @RequestMapping("/adminschool/adminechartsData")
    @ResponseBody
    public List<PieCount> adminechartsData(HttpServletRequest httpServletRequest){
        User user = (User) httpServletRequest.getSession().getAttribute("user");
        SchoolAdmin schoolAdmin = schoolAdminService.selectByUserId(user.getUserId());
        int schoolId = schoolAdmin.getSchoolId();
        List<PieCount> pieCountAdmin = schoolService.getPieCountAdmin(schoolId);
        return pieCountAdmin;
    }

然后前边的取值大概就是以下代码

       <script type="text/javascript">
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('main'));

        // 指定图表的配置项和数据
        option = {
            backgroundColor: '#2c343c',
            title: {
                text: 'Customized Pie',
                left: 'center',
                top: 20,
                textStyle: {
                    color: '#ccc'
                }
            },

            tooltip : {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },

            visualMap: {
                show: false,
                min: 80,
                max: 600,
                inRange: {
                    colorLightness: [0, 1]
                }
            },
            series : [
                {
                    name:'学校教师开课统计',
                    type:'pie',
                    radius : '55%',
                    center: ['50%', '50%'],
                    data:[
                    ],
                    roseType: 'angle',
                    label: {
                        normal: {
                            textStyle: {
                                color: 'rgba(255, 255, 255, 0.3)'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            lineStyle: {
                                color: 'rgba(255, 255, 255, 0.3)'
                            },
                            smooth: 0.2,
                            length: 10,
                            length2: 20
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: '#c23531',
                            shadowBlur: 200,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        // 异步加载数据
        $.get('/adminschool/adminechartsData').done(function (data) {
            // 填入数据
            myChart.setOption({
                series: [{
                    name:'学校教师开课统计',
                    type:'pie',
                    data: data
                }]
            });
        });

        // 使用刚指定的配置项和数据显示图表。
      //  myChart.setOption(option);
    </script>

上传多文件

单文件的上传

后台大概就这样

 @PostMapping("/course")
    public Map<String, Object> addCourse(MultipartFile multipartFile,
                                         @RequestParam(name = "title",required = true) String courseName ,
                                         @RequestParam(name = "desc" ,required = true) String courseInfo,
                                         @SessionAttribute User user,
                                         @RequestParam(name = "uuid") String courseUuid){
        log.warn("title desc " + courseInfo + courseName);
       Map<String,Object> map = new HashMap();
        //1 .获取原始文件名。
        String uploadFileName = multipartFile.getOriginalFilename();
        log.debug(uploadFileName+"原始文件名");
        String ext;
        if(uploadFileName.contains(".")){
            ext = uploadFileName.substring(uploadFileName.lastIndexOf("."));
        }else {
            ext = "";
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String newFileName = uuid + ext;

        File targetFile = new File(CoursePic_BASE_PATH,newFileName);
        try {
            multipartFile.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
            map.put("status",1);
        return map;
    }

前端是Layui框架写的

     <form class="layui-form" id="form1" enctype ="multipart/form-data" name = "form1">
            <div class="layui-form-item">
                <label class="layui-form-label">课程名字</label>
                <div class="layui-input-block">
                    <input style="width:20%;" type="text" name="title" id = "title"required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">类型选择框</label>
                <div class="layui-input-block" style="width: 20%">
                    <select name="city" lay-verify="required">
                        <option value=""></option>
                        <option value="0">编程类</option>
                        <option value="1">算法类</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">是否公开</label>
                <div class="layui-input-block">
                    <input type="checkbox" name="switch" lay-skin="switch">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">详细描述</label>
                <div class="layui-input-block">
                    <textarea name="desc" id = "desc" placeholder="请输入内容" class="layui-textarea"></textarea>
                </div>
            </div>
            <input type="hidden" name="uuid" id="uuid" />
            <div class="layui-form-item">
                <label class="layui-form-label">给课程来个封面图片吧</label>
                <div class="layui-input-block">
                    <input type="file" name="multipartFile" id="multipartFile" class="layui-btn layui-btn-lg"/>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
        <script>
        layui.use(['form','layer'], function(){
          var form = layui.form;
          form.on('submit(formDemo)', function(data){
              $('#uuid').val(new Date().getTime());
              var formData = new FormData($('#form1')[0]);
              console.log(formData);
              $.ajax({
                  type:"post",
                  url:"/teacher/course",
                  async:true,
                  data: formData,
                  contentType: false,
                  processData: false,
                  dataType: "json",
                  success:function (data) {
                      if(data.status == 1){
                          layer.alert('已经提交成功');
                          document.getElementById('form1').reset();
                      }else {
                          alert("处理错误")
                      }
                  },
                  error:function () {
                      alert("网络错误");
                  }
              });
            return false;
          });
        });
    </script>

多文件的上传

/**
     * 添加章节内容(上传文件)
     * @param uploadFile
     * @param title
     * @param courseId
     * @return
     */
    @PostMapping("chapter")
    public String addChapter(MultipartFile[] uploadFile,
                             @RequestParam(value = "title",required = true) String title,
                             @RequestParam(value = "courseId",required = true) int courseId,
                             @RequestParam(value="homeworklist",required = false) String[] homeworklist){

        //对于ppt和视频我们都加了后缀,
        String homework=homeworklist[0];
        for (int i=1;i<homeworklist.length;i++)
        {
                homework = homework+"====="+homeworklist[i];
        }
        System.out.println(homework);
        log.warn(homework);
        log.warn("准备上传ppt和视频");
        for (int i = 0; i < uploadFile.length; i++) {
            System.out.println(uploadFile[i].getOriginalFilename());
            System.out.println(uploadFile[i].isEmpty());
        }
        //循环获取文件
        String videoPath = saveFile(uploadFile[0], Video_BASE_PATH);
        String pptPath = saveFile(uploadFile[1], ChapterPPT_BASE_PATH);

        /** 添加章节
         *
         */
        Chapter chapter = new Chapter();
        chapter.setPath(videoPath);
        chapter.setPptPath(pptPath);
        chapter.setCourseId(courseId);
        log.warn(" courseId "+courseId);
        chapter.setChapterName(title);
        chapter.setHomework(homework);
        Integer maxIndex1 = chapterService.getMaxIndex(courseId);
        int maxIndex;
        if(maxIndex1==null||maxIndex1.intValue() == 0){
            maxIndex = 0;
        }else {
            maxIndex =maxIndex1.intValue();
        }
        chapter.setChapterIndex(++maxIndex);
        boolean flag = chapterService.addChapter(chapter);
        log.warn("上传完毕");
        return "/teacher/add_chapterOK";
    }
    private String saveFile(MultipartFile file, String path) {
        String uuid="ckin.mp4";
        String newFileName;
        if (!file.isEmpty()) {
            String uploadFileName = file.getOriginalFilename();
            log.debug(uploadFileName + "原始文件名");
            String ext;
            if (uploadFileName.contains(".")) {
                ext = uploadFileName.substring(uploadFileName.lastIndexOf("."));
            } else {
                ext = "";
            }
             uuid = UUID.randomUUID().toString().replaceAll("-", "");
             newFileName = uuid + ext;
            try {
                File filepath = new File(path);
                if (!filepath.exists())
                    filepath.mkdirs();
                // 文件保存路径
                String savePath = path + newFileName;
                log.warn("文件保存路径" + savePath +"文件的名字:"+newFileName);
                // 转存文件
                file.transferTo(new File(savePath));

                return newFileName;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else
            return uuid;
        return newFileName;
    }

前端代码

        <form class="layui-form" id="form1" enctype ="multipart/form-data" name = "form1">
            <div class="layui-form-item">
                <label class="layui-form-label">课程名字</label>
                <div class="layui-input-block">
                    <input style="width:20%;" type="text" name="title" id = "title"required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">类型选择框</label>
                <div class="layui-input-block" style="width: 20%">
                    <select name="city" lay-verify="required">
                        <option value=""></option>
                        <option value="0">编程类</option>
                        <option value="1">算法类</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">是否公开</label>
                <div class="layui-input-block">
                    <input type="checkbox" name="switch" lay-skin="switch">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">详细描述</label>
                <div class="layui-input-block">
                    <textarea name="desc" id = "desc" placeholder="请输入内容" class="layui-textarea"></textarea>
                </div>
            </div>
            <input type="hidden" name="uuid" id="uuid" />
            <div class="layui-form-item">
                <label class="layui-form-label">给课程来个封面图片吧</label>
                <div class="layui-input-block">
                    <input type="file" name="multipartFile" id="multipartFile" class="layui-btn layui-btn-lg"/>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
    <script>
        layui.use(['form','layer'], function(){
          var form = layui.form;
          form.on('submit(formDemo)', function(data){
              $('#uuid').val(new Date().getTime());
              var formData = new FormData($('#form1')[0]);
              console.log(formData);
              $.ajax({
                  type:"post",
                  url:"/teacher/course",
                  async:true,
                  data: formData,
                  contentType: false,
                  processData: false,
                  dataType: "json",
                  success:function (data) {
                      if(data.status == 1){
                          layer.alert('已经提交成功');
                          document.getElementById('form1').reset();
                      }else {
                          alert("处理错误")
                      }
                  },
                  error:function () {
                      alert("网络错误");
                  }
              });
            return false;
          });
        });
    </script>
  </body>

<script>
    function updddd() {
        $.ajax({
            type: "post",
            url: "/teacher/course",
            dataType: "json",
            contentType: false,
            data: {
                title: title,
                desc: desc,
                multipartFile: file
            },
            success: function (data) {
                alert(data);
                if (data.status == 1) {
                    $('#title').val("");
                    $('#desc').val("");
                    $('#uploadFile').val("");
                    layer.alert('已经提交成功');
                } else {
                    alert("处理错误")
                }
            },
            error: function () {
                alert("网络错误");
            }
        });
    }
</script>

下载PPT

服务端代码

@RequestMapping("/downloadppt/{path}")
    public void pptFiledownLoad(HttpServletRequest request,
                                HttpServletResponse response,
                                @PathVariable(name = "path") String path) {
        String downloadFilePath = ConstantMooc.ChapterPPT_BASE_PATH;//被下载的文件在服务器中的路径,
        String fileName = path;//被下载文件的名称
        File file = new File(downloadFilePath, fileName);
        if (file.exists()) {
            System.out.println("file下载 1");
            response.setContentType("application/force-download");// 设置强制下载不打开 
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            BufferedInputStream bis = null;
            OutputStream outputStream = null;
            try {
                System.out.println("file下载 2");
                bis = new BufferedInputStream(new FileInputStream(file));
                outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    bis.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

前端代码

<div class="x-body">
    <div class="layui-row">
        <form class="layui-form layui-col-md12 x-so">
            <input class ="layui-input" placeholder="课程id" type = "hidden" name = "courseId" id="courseId" th:value="${courseId}">
            <input type="text" name="username"  placeholder="课程名" autocomplete="off" class="layui-input">
            <button class="layui-btn"  lay-submit="" lay-filter="search"><i class="layui-icon">&#xe615;</i></button>
        </form>
    </div>
    <table style="display: none;" class="layui-hide" id="list" lay-filter="demo">
    </table>
</div>
</body>

<script th:inline="none">
    var tableIns;
    $(function(){
        layui.use(['form','table','layer','element'], function(){
            var form = layui.form;
            var table = layui.table;
            var layer = layui.layer;
            var courseId = $('#courseId').val();
            tableIns = table.render({
                elem: '#list',
                cellMinWidth: 80,
                url: '/chapter/'+courseId,
                id: 'list',
                toolbar: 'default' //开启工具栏,此处显示默认图标,可以自定义模板,详见文档
                , defaultToolbar : [ 'filter' ],
                cols:[[
                    {
                        title: '序号',
                        field:'zizeng',
                        unresize : true,
                        width:70,
                        type : 'numbers',

                    },
                    {
                        title: '章节号',
                        field:'chapterId',
                        hide:true,
                        align : 'left'
                    },
                    {
                        title: 'PPT路径',
                        field:'pptPath',
                        hide:true,
                        align : 'left'
                    },
                    {
                        title: '路径',
                        field:'path',
                        hide:true,
                        align : 'left'
                    },
                    {
                        title : '章节名',
                        field : 'chapterName',
                    },
                    {
                        title : '章节序号',
                        field : 'chapterIndex',
                    },
                    {
                        fixed: 'right',
                        width: 500,
                        align:'center',
                        toolbar: '#barDemo'
                    }
                ]]
            });

            /*操作列*/
            table.on('tool(demo)',function (obj) {
                var data =obj.data //获得当前行的数据
                    ,layEvent = obj.event; //获得 lay-event 对应的值
                var path = data.path;
                var pptPath =data.pptPath;
                var chapterName = data.chapterName;
                var chapterId =data.chapterId;
                if(layEvent === 'watch'){
                    window.location.href = "/videoWatch/"+path+"?chapterName="+chapterName+"&chapterId="+chapterId;
                }else  if(layEvent === 'ppt'){
                    if(pptPath==undefined && pptPath == null){
                        layer.msg("老师很懒,并没有上传")
                    }
                    else
                    downPptFile(data.pptPath);
                }else if(layEvent === 'homework'){
                    openhomework(data.chapterId)
                }else if(layEvent === "condition"){
                    x_admin_show('资讯','/gotostudyInfo?chapterId='+data.chapterId);
                }
            });
        });
    });
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="watch">观看</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="homework">作业</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="ppt">下载ppt</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="condition">该节学习情况</a>
</script>
<script>
    function downPptFile(path){
        var form=$("<form>");
        form.attr("style","display:none");
        form.attr("target","");
        form.attr("method","post");//提交方式为post
        form.attr("action","/downloadppt/"+path);//定义action
        $("body").append(form);
        form.submit();
    }
</script>
<script>
    function openhomework(chapterId){
        layui.use('layer',function () {
            var layer = layui.layer;
            var body;
            var index = layer.open({
                type: 2,
                skin: 'layui-layer-rim', //加上边框
                area: ['700px', '500px'], //宽高
                content: '/teacher/homework?chapterId='+chapterId,
                title : '作业',
                maxmin: true,
                success : function(layero, index) {
                    body = layer.getChildFrame('body', index);
                },
                yes : function(layero, index) {
                    var body = layer.getChildFrame('body', index);//获取子页面内容

                },
                end : function() {
                    tableIns.reload({});
                }
            });
            layer.full(index);
        });
        return false;
    }
</script>

code因为设计个人隐私没法上传,谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值