在获取请求中传递名称中带有空格的文件名

时间:2019-03-21 18:19:08

标签: java filenames get-request

我有一个文件的两个副本。一个是CatBoarding.mp4,另一个是Cat Boarding.mp4

当我执行:http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video=CatBoarding.mp4的chrome时效果很好。

但是,当我尝试:

  1. http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video="Cat Boarding.mp4"
  2. http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video='Cat Boarding.mp4'
  3. http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video=Cat Boarding.mp4
  4. http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video=Cat%20Boarding.mp4

找不到文件。我确实注意到,浏览器在每种情况下都会为该空格插入%20

@the_storyteller发现问题不是我如何将参数传递给jsp,而是我如何在jsp内部使用参数。最初,我们在jsp文件中:

<source src= <%= "../../videos/" + video %> type='video/mp4'>

这最终看起来像:

<source src= videos/Cat Boarding.mp4 type='video/mp4'>

有两种简单的解决方法:

  1. 在jsp文件中添加video = video.replace(" ","%20");
  2. 或更改

    <source src= <%= "'../../videos/" + video + "'" %> type='video/mp4'>

1 个答案:

答案 0 :(得分:0)

对不起,如果我不明白为什么您将此问题标记为Java问题,希望对您有所帮助:

请记住,URL / URN中的“空格”被视为不安全字符。 RFC1630说:

  There is a conflict between the need to be able to represent many
  characters including spaces within a URI directly, and the need to
  be able to use a URI in environments which have limited character
  sets or in which certain characters are prone to corruption.  This
  conflict has been resolved by use of an hexadecimal escaping
  method which may be applied to any characters forbidden in a given
  context.  When URLs are moved between contexts, the set of
  characters escaped may be enlarged or reduced unambiguously.

  The use of white space characters is risky in URIs to be printed
  or sent by electronic mail, and the use of multiple white space
  characters is very risky.  This is because of the frequent
  introduction of extraneous white space when lines are wrapped by
  systems such as mail, or sheer necessity of narrow column width,
  and because of the inter-conversion of various forms of white
  space which occurs during character code conversion and the
  transfer of text between applications.  This is why the canonical
  form for URIs has all white spaces encoded.

所以我认为,如果您需要在代码中使用“风险”或“模糊” URI,只需将危险字符替换为它们的百分比编码代码(%20表示空格,%3C表示“ <”等)。

解决此问题的另一种方法是,以您的情况保存您的视频文件,其名称更安全,称为“子弹”,用户和系统(例如搜索引擎或http客户端)都更易于阅读。

例如,法语标题使用可能引起相同问题的字符(é,è,î,à,ç等)。使用slug,您可以先更改文件,然后再将其保存到服务器,所有“空格”都会以您选择的字符(例如“-”或“ _”)出现。

Java中的Slugify(com.github.slugify)可以帮助您做到这一点