spring mvc中restcontroller的套路

本文介绍了一个基于HTTP的天气查询接口的设计与实现方案,包括定义Java类WeatherResponse用于封装返回的数据,实现WeatherDataService接口以提供根据城市ID或城市名称获取天气信息的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:
http://www.importnew.com/27014.html


public class WeatherResponse implements Serializable {

private static final long serialVersionUID = 1L;

private Weather data; // 消息数据
private String status; // 消息状态
private String desc; // 消息描述

public Weather getData() {
return data;
}

public void setData(Weather data) {
this.data = data;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

public String getDesc() {
return desc;
}

public void setDesc(String desc) {
this.desc = desc;
}

}


接口:

public interface WeatherDataService {

/**
* 根据城市ID查询天气数据
* @param cityId
* @return
*/
WeatherResponse getDataByCityId(String cityId);

/**
* 根据城市名称查询天气数据
* @param cityId
* @return
*/
WeatherResponse getDataByCityName(String cityName);
}

实现:

@Service
public class WeatherDataServiceImpl implements WeatherDataService {

@Autowired
private RestTemplate restTemplate;

private final String WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini";

@Override
public WeatherResponse getDataByCityId(String cityId) {
String uri = WEATHER_API + "?citykey=" + cityId;
return this.doGetWeatherData(uri);
}

@Override
public WeatherResponse getDataByCityName(String cityName) {
String uri = WEATHER_API + "?city=" + cityName;
return this.doGetWeatherData(uri);
}

private WeatherResponse doGetWeatherData(String uri) {
ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
String strBody = null;

if (response.getStatusCodeValue() == 200) {
strBody = response.getBody();
}

ObjectMapper mapper = new ObjectMapper();
WeatherResponse weather = null;

try {
weather = mapper.readValue(strBody, WeatherResponse.class);
} catch (IOException e) {
e.printStackTrace();
}

return weather;
}

}


控制器:

@RestController
@RequestMapping("/weather")
public class WeatherController {

@Autowired
private WeatherDataService weatherDataService;

@GetMapping("/cityId/{cityId}")
public WeatherResponse getReportByCityId(@PathVariable("cityId") String cityId) {
return weatherDataService.getDataByCityId(cityId);
}

@GetMapping("/cityName/{cityName}")
public WeatherResponse getReportByCityName(@PathVariable("cityName") String cityName) {
return weatherDataService.getDataByCityName(cityName);
}

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值