好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

解决@PathVariable对于特殊字符截断的问题

概述:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

@ResponseBody

  @RequestMapping (value= "/download/{fileName:[a-zA-Z0-9\\.\\-\\_]+}" , method = RequestMethod.GET)

  public void downloadAmr( HttpServletRequest request, HttpServletResponse response, @PathVariable ( "fileName" ) String fileName) {

  response.setContentType( "application/octet-stream" );

  String dir = System.getProperty( "catalina.home" ); //获得tomcat所在的工作路径

  System.out.println( "tomcat路径=" + dir);

  //获取到存储了文件存储位置的filedir.properties 文件路径

  String dir2 = dir.substring( 0 , dir.length()) + File.separator + "webapps" + File.separator + "ROOT" + File.separator + fileName;

  File file = new File(dir2);

  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  byte [] buffer = new byte [ 1024 ];

  int len;

  try {

  InputStream inputStream = new FileInputStream(file);

  while ((len = inputStream.read(buffer)) > - 1 ) {

  byteArrayOutputStream.write(buffer, 0 , len);

  }

  byteArrayOutputStream.flush();

  response.getOutputStream().write(byteArrayOutputStream.toByteArray());

  } catch (FileNotFoundException e) {

  logger.error( "读取文件异常" , e);

  } catch (IOException e) {

  logger.error(e.getMessage(), e);

  }

  logger.info( "下载进入。。。。。。。。。。。。。。。。。" );

  }

总结:

1、默认值情况下 /download/{fileName}, 然后 @PathVariable("fileName"),

如果路径为/download/1.jpg的话,那么 fileName=1 而不是1.jpg,问题就是默认对于字符._-相关进行截断了。

2、解决方法就是

{fileName:[a-zA-Z0-9\\.\\-\\_]+}

用正则表达式表示这些字符不能被截断。

补充:Springboot用@PathVariable传参,最后一个参数会丢失小数点后面的部分

当使用@PathVariable传递路径参数时,竟然神奇的发现,后面一位参数的小数点后面部分竟然不见啦,如下代码:

Controller方法注解如下:

?

1

@RequestMapping (value = "/user/findPassword/{email}" , method = RequestMethod.GET, produces= "application/json" )

我这里是想传递个邮箱过来的,然后就发现了没有邮箱后缀。

百思不得其解,遂百度之,解决方法如下:

?

1

@RequestMapping (value = "/user/findPassword/{email:.+}" , method = RequestMethod.GET, produces= "application/json" )

在参数后面添加个冒号和一个小数点在加上一个加号:{email:.+}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/m0_37355951/article/details/77113621

查看更多关于解决@PathVariable对于特殊字符截断的问题的详细内容...

  阅读:25次