java - 添加到 ModelAndView 的变量似乎消失了

标签 java spring jsp

我试图在我的 Spring MVC/jsp 项目中获取文件上传页面,并且文件上传正确。它在日志文件中输出文件名,然后我将文件名添加到 ModelAndView 中,当我尝试在 View (.jsp 文件)中访问它们时,它们似乎不存在......但我添加的另一个对象确实存在......

这是我将文件名添加到 ModelAndView 的 Controller :

@RequestMapping(value = "/uploadFiles.html", method = RequestMethod.POST)
public String save(@ModelAttribute Token token, @ModelAttribute("uploadForm") FileUpload fileUpload, ModelAndView mav)
{
    List<MultipartFile> files = fileUpload.getFiles();

    List<String> fileNames = new ArrayList<String>();

    if(files != null && files.size() > 0)
    {
        for(MultipartFile file : files)
        {
            if(!file.isEmpty())
            {
                fileNames.add(file.getOriginalFilename());
                logger.info("Got file with name: " + file.getOriginalFilename());
            }
        }

        logger.info("Total filenames: " + fileNames.size());
    }

    mav.addObject("files",fileNames);
    mav.addObject("token",token);
    return "etl/EtlUploadSuccess";
}

日志输出显示它正在工作:

09:51:09,072 INFO  [Controller] [http-bio-8080-exec-4] Got file with name: ExcelFileOne.xlsx
09:51:09,085 INFO  [Controller] [http-bio-8080-exec-4] Got file with name: ExcelFileTwo.xls
09:51:09,096 INFO  [Controller] [http-bio-8080-exec-4] Total filenames: 2

这是成功页面的代码片段,其中应显示文件名:

    <p>The following files have been uploaded successfully with the token ${token.name}:</p>
    <c:forEach items="${files}" var="file">
        ${file}<br/>
    </c:forEach>

页面显示:

The following files have been uploaded successfully with the token testToken:

就是这样...我很困惑为什么文件名没有显示...

最佳答案

尝试更改方法签名以返回 ModelAndView,如下所示

@RequestMapping(value = "/uploadFiles.html", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute Token token, @ModelAttribute("uploadForm")    FileUpload fileUpload) 
{
    List<MultipartFile> files = fileUpload.getFiles();

    List<String> fileNames = new ArrayList<String>();

    if(files != null && files.size() > 0)
    {
        for(MultipartFile file : files)
        {
            if(!file.isEmpty())
            {
                fileNames.add(file.getOriginalFilename());
            logger.info("Got file with name: " + file.getOriginalFilename());
            }
        }

        logger.info("Total filenames: " + fileNames.size());
    }

    ModelAndView mav = new ModelAndView("etl/EtlUploadSuccess");
    mav.addObject("files",fileNames);
    mav.addObject("token",token);
    return mav;
}

注意我还删除了该方法的 ModelAndView 参数

关于java - 添加到 ModelAndView 的变量似乎消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17926284/

相关文章:

java - Spring Boot YAML 配置和列表

java - 无法读取 HTTP 消息。缺少必需的请求正文

java - 每次进行更改时都重建整个 Java 应用程序

java - 确定 Postscript 打印支持

java - Mockito 异常 : Missing method invocation while trying to test an if conditon

java - 转换 Cucumber 中的数据表

java - 我可以让我的数据提取程序(oracle数据库到excel)更加高效吗?

java - JSP获取html类型=数字输入字段的值

osx-mountain-lion - OSX 上的 Java 7 配置说明

java - Maven 3 工件问题