Troubleshoot @ PathVariable for special character truncation
- 2021-08-28 20:06:40
- OfStack
Overview:
@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"); // Obtain tomcat The working path in which
System.out.println("tomcat Path =" + dir);
// Object where the file is stored filedir.properties File path
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(" File read exception ", e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
logger.info(" Download and enter. . . . . . . . . . . . . . . . . ");
}
Summary:
1. In the default case/download/{fileName}, then @ PathVariable ("fileName"),
If the path is/download/1. jpg, then fileName=1 instead of 1. jpg, the problem is that the character. _-correlation is truncated by default.
2. The solution is
{fileName:[a-zA-Z0-9\\.\\-\\_]+}
Use regular expressions to indicate that these characters cannot be truncated.
Supplement: Springboot uses @ PathVariable to pass parameters, and the last parameter will lose the part after the decimal point
When using @ PathVariable to pass the path parameter, it was magically found that the part behind the decimal point of the last 1-digit parameter was missing, as follows:
The Controller method is annotated as follows:
@RequestMapping(value = "/user/findPassword/{email}", method = RequestMethod.GET, produces="application/json")
I want to pass a mailbox here, and then I found that there is no mailbox suffix.
Confused, Baidu's solution is as follows:
@RequestMapping(value = "/user/findPassword/{email:.+}", method = RequestMethod.GET, produces="application/json")
Add a colon and a decimal point after the parameter and add a plus sign: {email:. +}