註解@RequestParam與@PathVariable的區別
阿新 • • 發佈:2018-11-30
看下這段程式碼,顯示圖片的
@Controller
@RequestMapping(value = "/imgs")
public class ImgsController {
@Autowired
private HdfsFileService hdfsFileService;
/**
* 顯示圖片
* @return
*/
@RequestMapping("/showc/{id}")
@ResponseBody
public String showc(@PathVariable String id, HttpServletRequest request, HttpServletResponse response)
throws Exception {
FileSystem fs = hdfsFileService.getFileSystem();
InputStream in = null;
try {
in = fs.open(new Path("/kddata/food/finishprotectfingure/imgs/" + id));
IOUtils.copyBytes(in, response.getOutputStream(), 4096, false);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
IOUtils.closeStream(in);
}
return null;
}
在瀏覽器上你只需輸localhost:8080/mananger/imgs/showc/uewaas12nwdqwd.img
.就能訪問到圖片,其中,每個圖片名字是不同的,所以{id}是動態的,這個時候要獲取url中的這個動態引數,就用到了註解@PathVariable
@PathVariable 將請求URL中的模板變數對映到功能處理方法的引數。
在SpringMVC後臺控制層獲取引數的方式主要有兩種:
一種是request.getParameter(“name”),另外一種是用註解@RequestParam直接獲取
value:引數名字,即入參的請求引數名字,如username表示請求的引數區中的名字為username的引數的值將傳入;
@RequestMapping("/test")
@ResponseBody
public String test3(@RequestParam(value="username") String username,HttpServletRequest request){
String age = request.getParameter("age");
return username;
}