Spring @RequestMapping
我一直在Spring的@RequestMapping
注释中看到这种参数value = "/redirect/{id}"
。 我一直在想这里{id}
是什么? 这是某种Expression Language
吗?
我看到的示例代码:
@RequestMapping( value = "/files/{id}", method = RequestMethod.GET ) public void getFile( @PathVariable( "id" ) String fileName, HttpServletResponse response ) { try { // get your file as InputStream InputStream is = new FileInputStream("/pathToFile/"+ fileName); // copy it to response's OutputStream IOUtils.copy( is, response.getOutputStream() ); response.flushBuffer(); } catch( IOException ex ) { throw new RuntimeException( "IOError writing file to output stream" ); } }
我的问题是映射中的{id}
是什么,它与@PathVariable
注释的关系是什么以及如何使用它? 我从网上获得了一些信息,但我会更加欣赏你们,听到你们更清楚的解释。
@RequestMapping
值中的{foo}
部分是路径变量,表示从url路径而不是从request参数检索的值。
例如,如果用户访问/files/foo.zip
,那么{id}
将匹配foo.zip
并告诉Spring将该值存储到具有注释@PathVariable("id")
的变量中。
您可以在@RequestMapping
注释值的URL标识符中包含多个路径变量,并且可以使用在大括号内使用的相同ID的@PathVariable
将这些值注入变量。
我想你的例子是,通过浏览../files/1或../files/2或../files/3,数字代表不同的文件名。 @PathVariable(“id”)可以帮助您节省写入不同参数function的时间。
{id}是我们正在传递的url查询字符串,并使用@PathVariable(“id”)检索该id并作为参数传递给方法,一种方法适合于此处更改id的不同请求。 谢谢。
@RequestMapping( value = "/files/{id}", method = RequestMethod.GET ) public void getFile( @PathVariable( "id" ) **String id**) String fileName, HttpServletResponse response ) { //your code here }
pathvariable使用method参数映射你的uri。 这里id是你发送的请求,例如。 /文件/ 7。
- 如何调用MethodInvoke – reflection
- 线程“AWT-EventQueue-0”中的exceptionjava.lang.ClassCastException:javax.swing.JTable
- 从websphere 8.5.5.2访问ssl Web服务
- Java CRC32:与C#中的CRC不同
- 使用相同的字符串文字而不是最终变量?
- jdbc4 CommunicationsException
- 在Java中使用\ b Boundary Matcher
- NoSuchMethodError:com.google.common.util.concurrent.MoreExecutors.directExecutor在Elastic Search jar上进行conflits
- Java中监听器的目的是什么?