Check the weather achieve spring boot project function

Spring boot project for query function Weather

When the weather for query functions: json analytic uses, the whole idea is to use the interface return query results and then parse the string, set to bind the entity classes and then by model, thymleaf the front display.

Directly on the code

// import dependencies in pom.xml file

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.7</version>
    </dependency>
      <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.2.3</version>
            <classifier>jdk15</classifier>
        </dependency>
        
//天气实体类
package com.select.wuliu.entity;

import java.io.Serializable;
import java.util.List;

public class WeatherData implements Serializable{

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/** 昨日天气情况 .*/
    private Yesterday yesterday;

    /** 未来七日预测 .*/
    private List<Forecast> forecast;

    /** 城市 .*/
    private String city;

    /** 空气指数 .*/
    private String aqi;

    /** 提示 .*/
    private String ganmao;

    /** 温度 .*/
    private String wendu;

	public Yesterday getYesterday() {
		return yesterday;
	}

	public void setYesterday(Yesterday yesterday) {
		this.yesterday = yesterday;
	}

	public List<Forecast> getForecast() {
		return forecast;
	}

	public void setForecast(List<Forecast> forecast) {
		this.forecast = forecast;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getAqi() {
		return aqi;
	}

	public void setAqi(String aqi) {
		this.aqi = aqi;
	}

	public String getGanmao() {
		return ganmao;
	}

	public void setGanmao(String ganmao) {
		this.ganmao = ganmao;
	}

	public String getWendu() {
		return wendu;
	}

	public void setWendu(String wendu) {
		this.wendu = wendu;
	}

	@Override
	public String toString() {
		return "WeatherData [yesterday=" + yesterday + ", forecast=" + forecast + ", city=" + city + ", aqi=" + aqi
				+ ", ganmao=" + ganmao + ", wendu=" + wendu + "]";
	}
    
}
//昨天实体类
package com.select.wuliu.entity;

import java.io.Serializable;

public class Yesterday implements Serializable{

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/** 日期 .*/
    private String date;

    /** 最高温度 .*/
    private String high;

    /** 风向 .*/
    private String fx;

    /** 最低温度 .*/
    private String low;

    /** 风力 .*/
    private String fl;

    /** 天气情况 .*/
    private String type;

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getHigh() {
		return high;
	}

	public void setHigh(String high) {
		this.high = high;
	}

	public String getFx() {
		return fx;
	}

	public void setFx(String fx) {
		this.fx = fx;
	}

	public String getLow() {
		return low;
	}

	public void setLow(String low) {
		this.low = low;
	}

	public String getFl() {
		return fl;
	}

	public void setFl(String fl) {
		this.fl = fl;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	@Override
	public String toString() {
		return "Yesterday [date=" + date + ", high=" + high + ", fx=" + fx + ", low=" + low + ", fl=" + fl + ", type="
				+ type + "]";
	}
    
}
//预报实体类
package com.select.wuliu.entity;

import java.io.Serializable;

public class Forecast implements Serializable {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/** 日期 .*/
    private String date;

    /** 最高温度 .*/
    private String high;

    /** 风力 .*/
    private String fengli;

    /** 最低温度 .*/
    private String low;

    /** 风向 .*/
    private String fengxiang;

    /** 天气情况 .*/
    private String type;

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getHigh() {
		return high;
	}

	public void setHigh(String high) {
		this.high = high;
	}

	public String getFengli() {
		return fengli;
	}

	public void setFengli(String fengli) {
		this.fengli = fengli;
	}

	public String getLow() {
		return low;
	}

	public void setLow(String low) {
		this.low = low;
	}

	public String getFengxiang() {
		return fengxiang;
	}

	public void setFengxiang(String fengxiang) {
		this.fengxiang = fengxiang;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	@Override
	public String toString() {
		return "Forecast [date=" + date + ", high=" + high + ", fengli=" + fengli + ", low=" + low + ", fengxiang="
				+ fengxiang + ", type=" + type + "]";
	}

}






## 配置config
package com.select.wuliu.shiro;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;


@Configuration
public class WeatherConfig {
    @Bean
    //设置字符集同时保证回传的字符不出现乱码
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}
//controller 控制器
package com.select.wuliu.controller;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.select.wuliu.controller.exeception.warnException;
import com.select.wuliu.entity.Forecast;
import com.select.wuliu.entity.WeatherData;
import com.select.wuliu.entity.Yesterday;
import com.select.wuliu.service.RedisService;
import com.select.wuliu.util.ResponseResult;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
/***
 * 天气
 * @author Admin
 *
 */
public class QueryWeather extends BaseController {
	@Autowired
	RestTemplate restTemplate;
	@GetMapping("/charts-7")
	public String charts7(String city,Model model){
		String apiURL = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
		ResponseEntity<String> responseEntity = restTemplate.getForEntity(apiURL, String.class);
		//获得所有回传的消息
		String jsonsting=responseEntity.getBody();
		WeatherData wed=new WeatherData();
		JSONObject str =JSONObject.fromObject(jsonsting);
	//	第一步解析
		String status="";
		if(str.has("status")){
		status=	str.get("status").toString();
		//如果输入的城市不对回传的状态码不同
		}
		if(status.equals("1000")){
		
		if(str.has("data")){
			//获取正确的数据
			JSONObject str1 =JSONObject.fromObject(str.get("data"));
			if(str1.has("yesterday")){
				//获取昨天数据
				JSONObject yy =JSONObject.fromObject(str1.get("yesterday"));
				//set到昨天实体类
				
				Yesterday y=new Yesterday();
				y.setDate(yy.getString("date"));
				y.setFl(yy.getString("fl"));
				y.setFx(yy.getString("fx"));
				y.setHigh(yy.getString("high"));
				y.setLow(yy.getString("low"));
				y.setType(yy.getString("type"));
				
				wed.setYesterday(y);
			}
			//预报
			List<Forecast> fc=new ArrayList<Forecast>();
			if(str1.has("forecast")){
				//System.err.println(str1.get("forecast"));  
				JSONArray tr=str1.getJSONArray("forecast");
				for (int i = 0; i < tr.size(); i++) {
					JSONObject yy1=JSONObject.fromObject(tr.get(i)); 
					Forecast f=new Forecast();
					f.setDate(yy1.getString("date"));
					f.setFengli(yy1.getString("fengli"));
					f.setFengxiang(yy1.getString("fengxiang"));
					f.setHigh(yy1.getString("high"));
					f.setLow(yy1.getString("low"));
					f.setType(yy1.getString("type"));
				//	System.err.println(f+"f"); 
					fc.add(f);
				}
				wed.setForecast(fc);
			}
			//感冒指数
			if(str1.has("ganmao")){
				//System.err.println(str1.get("ganmao"));  
				wed.setGanmao(str1.get("ganmao").toString());
			}
			//城市
			if(str1.has("city")){
				//System.err.println(str1.get("city"));  
				wed.setCity(str1.get("city").toString());
			}
			//温度
			if(str1.has("wendu")){
			//	System.err.println(str1.get("wendu")); 
				wed.setWendu(str1.get("wendu").toString());
			}
			//System.err.println(wed+"wed");
			model.addAttribute("WeatherData", wed);
		}
		
		
		}else{
			throw new warnException("请输入正确的城市名称!");
		}
		
		return "charts-7";
	}

}
//前端thymleaf
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<!--[if lt IE 9]>
<script type="text/javascript" src="lib/html5shiv.js"></script>
<script type="text/javascript" src="lib/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="/h-ui/css/H-ui.min.css" />
<link rel="stylesheet" type="text/css" href="/h-ui.admin/css/H-ui.admin.css" />
<link rel="stylesheet" type="text/css" href="lib/Hui-iconfont/1.0.8/iconfont.css" />
<link rel="stylesheet" type="text/css" href="/h-ui.admin/skin/default/skin.css" id="skin" />
<link rel="stylesheet" type="text/css" href="/h-ui.admin/css/style.css" />
<!--[if IE 6]>
<script type="text/javascript" src="lib/DD_belatedPNG_0.0.8a-min.js" ></script>
<script>DD_belatedPNG.fix('*');</script>
<![endif]-->
<title>天气预报</title>
</head>
<body>
<nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i> 首页 <span class="c-gray en">&gt;</span> 
个人收藏 <span class="c-gray en">&gt;</span> 天气预报 <a class="btn btn-success radius r" style="line-height:1.6em;margin-top:3px" href="javascript:location.replace(location.href);" title="刷新" ><i class="Hui-iconfont">&#xe68f;</i></a></nav>
<div>
        <p>
            城市:<span th:text="${WeatherData.city}"></span>
            温度:<span th:text="${WeatherData.wendu}"></span>
            友情提示:<span th:text="${WeatherData.ganmao}"></span>
        </p>
        <p>
            日期:<span th:text="${WeatherData.yesterday.date}"></span>
        </p>
        <p>
            最高温度:<span th:text="${WeatherData.yesterday.high}"></span>
            最低温度:<span th:text="${WeatherData.yesterday.low}"></span>
            风向:<span th:text="${WeatherData.yesterday.fx}"></span>
            风力:<span th:text="${WeatherData.yesterday.fl}"></span>
            天气情况:<span th:text="${WeatherData.yesterday.type}"></span>
        </p>
    </div>
    <div th:each="forecast : ${WeatherData.forecast}">
        <p>
            日期:<span th:text="${forecast.date}"></span>
        </p>
        <p>
            最高温度:<span th:text="${forecast.high}"></span>
            最低温度:<span th:text="${forecast.low}"></span>
            风向:<span th:text="${forecast.fengxiang}"></span>
            风力:<span th:text="${forecast.fengli}"></span>
            天气情况:<span th:text="${forecast.type}"></span>
        </p>
    </div>





<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="lib/jquery/1.9.1/jquery.min.js"></script> 
<script type="text/javascript" src="lib/layer/2.4/layer.js"></script>
<script type="text/javascript" src="/h-ui/js/H-ui.min.js"></script> 
<script type="text/javascript" src="/h-ui.admin/js/H-ui.admin.js"></script> <!--/_footer 作为公共模版分离出去-->

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="lib/hcharts/Highcharts/5.0.6/js/highcharts.js"></script>
<script type="text/javascript" src="lib/hcharts/Highcharts/5.0.6/js/modules/exporting.js"></script>
<script type="text/javascript" src="lib/hcharts/Highcharts/5.0.6/js/highcharts-3d.js"></script>
<script type="text/javascript">

</script>
</body>
</html>


-

Guess you like

Origin blog.csdn.net/Wyangcsdb/article/details/91414868