springboot中根据url获取json

application.yml文件中配置:
file:
  dir: /mnt/mfs-cli/gf/
  #dir: E:\\Area\\anhui

在Controller文件中:
	@Value("${file.dir}")
    private String fileDir;
 
实际调用方法:
@SuppressWarnings({ "rawtypes", "unchecked" })
@ApiOperation(value = "根据json的url获取json", notes = "根据json的url获取json")
@GetMapping(value = "getJsonOrGeoJson")
public void getJsonOrGeoJson(@ApiParam(value = "json地址") @RequestParam String url,HttpServletResponse response) {
		log.info("根据json的url获取json");
	    PrintWriter out = null;  
	    try {  
		    File panelFile = new File(fileDir,url);
		    String panelInput = FileUtils.readFileToString(panelFile, "UTF-8");
		    JSONObject responseJSONObject = JSONObject.fromObject(panelInput);  
		    response.setCharacterEncoding("UTF-8");  
		    response.setContentType("application/json; charset=utf-8");  
	        out = response.getWriter();  
	        out.append(responseJSONObject.toString());  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    } finally {  
	        if (out != null) {  
	            out.close();  
	        }  
	    }  
}
Spring Boot控制器(Controller)接收URL参数是一种常见的Web开发实践,用于获取客户端传递给服务器的数据。在Spring Boot,可以通过多种方式来接收URL参数,主要方法如下: 1. 使用`@PathVariable`注解:这个注解用于获取URL模板的参数。通常用在RESTful API的路径变量上。例如,定义一个接口,该接口的URL是`/users/{id}`,你可以通过`@PathVariable("id")`来获取URL的`id`值。 ```java @GetMapping("/users/{id}") public String getUser(@PathVariable("id") String id) { // 处理逻辑,例如根据id查询用户信息 return "User ID is: " + id; } ``` 2. 使用`@RequestParam`注解:这个注解用于获取URL查询参数。查询参数通常位于URL的问号(?)之后,以键值对的形式出现,多个参数之间使用`&`符号分隔。例如,`/search?name=John&age=30`的`name`和`age`可以通过`@RequestParam`来接收。 ```java @GetMapping("/search") public String searchUser(@RequestParam("name") String name, @RequestParam("age") int age) { // 处理逻辑,例如根据name和age查询用户信息 return "Searching for user with name: " + name + " and age: " + age; } ``` 3. 使用`@RequestBody`注解:虽然这不是直接获取URL参数,但`@RequestBody`用于接收请求体JSON或XML格式的数据。这个注解通常用在POST或PUT等请求,用来获取请求体的内容。 ```java @PostMapping("/users") public String createUser(@RequestBody User user) { // 处理逻辑,例如创建用户信息 return "User created with name: " + user.getName(); } ``` 4. 使用`@MatrixVariable`注解(高级用法,需开启支持):Spring Boot默认是不支持矩阵变量的,需要手动开启。矩阵变量是URL的一种参数,其格式通常为`/path;paramName=value;paramName2=value2`。 ```java @GetMapping("/items/{id};color={color}") public String getItem(@PathVariable("id") Long id, @MatrixVariable("color") String color) { // 处理逻辑,例如根据id和颜色获取商品信息 return "Item ID is: " + id + " and color is: " + color; } ``` 要注意的是,Spring Boot对矩阵变量的支持不是默认开启的,需要在配置特别开启。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值