springboot实战——搭建天气查询网站

天气查询的api:https://www.sojson.com/open/api/weather/json.shtml?city=北京,返回json数据

格式如下:

{
    "date": "20180428",
    "message": "Success !",
    "status": 200,
    "city": "北京",
    "count": 1043,
    "data": {
        "shidu": "45%",
        "pm25": 39,
        "pm10": 161,
        "quality": "轻度污染",
        "wendu": "18",
        "ganmao": "儿童、老年人及心脏、呼吸系统疾病患者人群应减少长时间或高强度户外锻炼",
        "yesterday": {
            "date": "27日星期五",
            "sunrise": "05:22",
            "high": "高温 27.0℃",
            "low": "低温 13.0℃",
            "sunset": "19:04",
            "aqi": 111,
            "fx": "南风",
            "fl": "3-4级",
            "type": "晴",
            "notice": "愿你拥有比阳光明媚的心情"
        },
        "forecast": [
            {
                "date": "28日星期六",
                "sunrise": "05:21",
                "high": "高温 27.0℃",
                "low": "低温 17.0℃",
                "sunset": "19:05",
                "aqi": 102,
                "fx": "西南风",
                "fl": "3-4级",
                "type": "晴",
                "notice": "愿你拥有比阳光明媚的心情"
            },
            {
                "date": "29日星期日",
                "sunrise": "05:19",
                "high": "高温 29.0℃",
                "low": "低温 17.0℃",
                "sunset": "19:06",
                "aqi": 97,
                "fx": "南风",
                "fl": "<3级",
                "type": "多云",
                "notice": "阴晴之间,谨防紫外线侵扰"
            },
            {
                "date": "30日星期一",
                "sunrise": "05:18",
                "high": "高温 23.0℃",
                "low": "低温 14.0℃",
                "sunset": "19:07",
                "aqi": 61,
                "fx": "东南风",
                "fl": "<3级",
                "type": "多云",
                "notice": "阴晴之间,谨防紫外线侵扰"
            },
            {
                "date": "01日星期二",
                "sunrise": "05:17",
                "high": "高温 23.0℃",
                "low": "低温 14.0℃",
                "sunset": "19:08",
                "aqi": 52,
                "fx": "北风",
                "fl": "4-5级",
                "type": "阴",
                "notice": "不要被阴云遮挡住好心情"
            },
            {
                "date": "02日星期三",
                "sunrise": "05:16",
                "high": "高温 23.0℃",
                "low": "低温 12.0℃",
                "sunset": "19:09",
                "aqi": 49,
                "fx": "东北风",
                "fl": "3-4级",
                "type": "多云",
                "notice": "阴晴之间,谨防紫外线侵扰"
            }
        ]
    }
}


项目结构如下:



todayweather(保存今日天气情况)
package com.example.demo;
/*
 * 用于表示本天天气
 */
public class todayweather {
      
private String shidu;
private String pm25;
private String pm10;
private String quality;
private String wendu;
private String ganmao;
	
public String getShidu() {
return shidu;
}
public void setShidu(String shidu) {
this.shidu = shidu;
}
public String getPm25() {
return pm25;
}
public void setPm25(String pm25) {
this.pm25 = pm25;
}
public String getPm10() {
return pm10;
}
public void setPm10(String pm10) {
this.pm10 = pm10;
}
public String getQuality() {
return quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
public String getWendu() {
return wendu;
}
public void setWendu(String wendu) {
this.wendu = wendu;
}
public String getGanmao() {
return ganmao;
}
public void setGanmao(String ganmao) {
this.ganmao = ganmao;
}
}

weather(保存昨天与明后几天的天气状况)
package com.example.demo;

/*
 * 用于表示weather中的json格式
 */
public class Weather {
	
   String date;
   String sunrise;
   String high;
   String low;
   String sunset;
   String aqi;
   String fx;
   String fl;
   String type;
   String notice;
   
public String getDate() {
	return date;
}
public void setDate(String date) {
	this.date = date;
}
public String getSunrise() {
	return sunrise;
}
public void setSunrise(String sunrise) {
	this.sunrise = sunrise;
}
public String getHigh() {
	return high;
}
public void setHigh(String high) {
	this.high = high;
}
public String getLow() {
	return low;
}
public void setLow(String low) {
	this.low = low;
}
public String getSunset() {
	return sunset;
}
public void setSunset(String sunset) {
	this.sunset = sunset;
}
public String getAqi() {
	return aqi;
}
public void setAqi(String aqi) {
	this.aqi = aqi;
}
public String getFx() {
	return fx;
}
public void setFx(String fx) {
	this.fx = fx;
}
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;
}
public String getNotice() {
	return notice;
}
public void setNotice(String notice) {
	this.notice = notice;
} 
}

returnweather(用于返回保存天气信息的对象)
package com.example.demo;

import java.io.IOException;
import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/*
 * 用于返回今天和昨天以及未来的天气状况
 */
@Service
public class returnweather {
	//用于解析JSON数据	
	private JsonNode json=null;
	private final String uri="https://www.sojson.com/open/api/weather/json.shtml?city=";
	

	private boolean getjsondata(String city) {
		RestTemplate rest=new RestTemplate();
		ResponseEntity<String> response=rest.getForEntity(uri+city,String.class);//发送请求获取JSON信息
		
		if(response.getStatusCodeValue()==200) {
		String strbody=response.getBody();
		ObjectMapper mapper=new ObjectMapper();
		try {
			json=mapper.readTree(strbody);
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.print("json初始化失败");
			e.printStackTrace();
		}
	    }
		return false;
	}
	
	public todayweather gettodayweather(String city) {
		if(json==null) 	{
			boolean judge = getjsondata(city);
			if(judge==false) return null; 
		}
		todayweather result=new todayweather();
		try {			    
			JsonNode data=json.get("data");
			result.setShidu(data.get("shidu").toString());
			result.setGanmao(data.get("ganmao").toString());
			result.setPm10(data.get("pm10").toString());
			result.setPm25(data.get("pm25").toString());
			result.setQuality(data.get("quality").toString());
			result.setWendu(data.get("wendu").toString());
		}catch(Exception e) {
			System.out.print("获取当天天气状况失败");
			e.printStackTrace();
			return null;
		}
		
		return result;
	}
	
	private Weather returnwth(JsonNode deal) throws Exception{
		Weather result=new Weather();
		result.setAqi(deal.get("aqi").toString());
		result.setDate(deal.get("date").toString());
		result.setFl(deal.get("fl").toString());
		result.setFx(deal.get("fx").toString());
		result.setHigh(deal.get("high").toString());
		result.setLow(deal.get("low").toString());
		result.setNotice(deal.get("notice").toString());
		result.setSunrise(deal.get("sunrise").toString());
	    result.setSunset(deal.get("sunset").toString());
	    result.setType(deal.get("type").toString());
	    return result;
	}
	
	public Vector<Weather> getweatherList(String city){
		if(json==null) 	{
			boolean judge = getjsondata(city);
			if(judge==false) return null; 
		}
		Vector<Weather> result=new Vector<Weather>();
		try {
			JsonNode yd=json.get("data").get("yesterday");
			Weather yesterday=returnwth(yd);	
			Weather forecast;
			result.add(yesterday);
			JsonNode fc=json.get("data").get("forecast");
			for(int i=0;i<5;i++) {
				forecast=returnwth(fc.get(i));
			    result.add(forecast);
			}
		}catch(Exception e){
			e.printStackTrace();	
			return null;
			}
		return result;
	}
}

Weathercontroller(控制器)
package com.example.demo;

import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.RestController;

@Controller
@RequestMapping("/weather")
public class Weathercontroller {
   
	@Autowired
    returnweather deal;
	
	@RequestMapping(value="/{city}",method=RequestMethod.GET)
	public String getWatherinfo(@PathVariable("city") String city,Model model) {
		returnweather deal=new returnweather();
		todayweather weathertd=deal.gettodayweather(city);
		Vector<Weather> weatherset=deal.getweatherList(city);
		if(weathertd!=null) 
		{	
		   model.addAttribute("todayweather",weathertd);
		   model.addAttribute("weather", weatherset);
		}
		else
		{
			System.out.print("设置error");
			model.addAttribute("error", "查询次数过快或城市名称错误");
		}
		return "weather";		
	}
}

启动类
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WeatheReporter1Application
{

	public static void main(String[] args) {
		SpringApplication.run(WeatheReporter1Application.class, args);
	}
}


pom.xml(添加了jsp依赖以及打包成jar所需要的信息)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>WeatheReporter-1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>WeatheReporter-1</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
      <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jdt.core.compiler</groupId>
            <artifactId>ecj</artifactId>
            <version>4.6.1</version>
            <scope>provided</scope>
        </dependency>
	</dependencies>
	
	<build>
	<finalName>weather</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<version>1.4.2.RELEASE</version> 
			</plugin>
		</plugins>
	    <resources>  
            <!-- 打包时将jsp文件拷贝到META-INF目录下-->  
            <resource>  
                <!-- 指定resources插件处理哪个目录下的资源文件 -->  
                <directory>src/main/webapp</directory>  
                <!--注意此次必须要放在此目录下才能被访问到-->  
                <targetPath>META-INF/resources</targetPath>  
                <includes>  
                    <include>**/**</include>  
                </includes>  
            </resource> 
     </resources> 
	</build>

</project>


weather.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="com.example.demo.todayweather,com.example.demo.Weather,java.util.Vector"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
todayweather today=(todayweather)request.getAttribute("todayweather");
String error=(String)request.getAttribute("error");
Vector<Weather> weatherset=(Vector<Weather>)request.getAttribute("weather");
%>
<%
if(today!=null){
	out.print("<h2>今日天气</h2>");
	out.print("温度:"+today.getWendu());
	out.print("<br>");
	out.print("湿度:"+today.getShidu());
	out.print("<br>");
	out.print("温馨提示:"+today.getGanmao());
	out.print("<br>");
	out.print("空气质量:"+today.getQuality());
	out.print("<br>");
	out.print("Pm2.5:"+today.getPm25());
	out.print("<br>");
	out.print("PM1.0:"+today.getPm10());
	out.print("<br>");
}
if(weatherset!=null){
	int size=weatherset.size();
	for(int i=0;i<size;i++){
		if(i==0) out.print("<h2>昨日天气</h2>");
		else out.print("<h2>天气展望</h2>");
		out.print("时间:"+weatherset.get(i).getDate()+"<br>");
		out.print("日出:"+weatherset.get(i).getSunrise()+"<br>");
		out.print("最高气温:"+weatherset.get(i).getSunrise()+"<br>");
		out.print("最低气温:"+weatherset.get(i).getSunset()+"<br>");
		out.print("aqi:"+weatherset.get(i).getAqi()+"<br>");
		out.print("fx:"+weatherset.get(i).getFx()+"<br>");
		out.print("fl:"+weatherset.get(i).getFl()+"<br>");
		out.print("天气:"+weatherset.get(i).getType()+"<br>");
		out.print("温馨提示:"+weatherset.get(i).getNotice()+"<br>");
	}
}
if(error!=null){
	out.print(error);
}
%>
</body>
</html>

springboot的默认模板引擎为thymeleaf,添加以下依赖,将模板引擎改为jsp,jsp文件路径:src\main\webapp\WEB-INF\views,在配置文件中添加路径:

spring.mvc.view.prefix=/WEB-INF/views/

spring.mvc.view.suffix=.jsp

在本机上运行即可,但是打包成jar文件时,要去掉这两句,因为jsp文件的路径发生了改变,springboot可以默认访问


springboot默认不支持jsp,所以在编译成jar文件时,不会编译jsp,在pom.xml中添加如下语句:

	<build>
	<finalName>weather</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<version>1.4.2.RELEASE</version> 
			</plugin>
		</plugins>
	    <resources>  
            <!-- 打包时将jsp文件拷贝到META-INF目录下-->  
            <resource>  
                <!-- 指定resources插件处理哪个目录下的资源文件 -->  
                <directory>src/main/webapp</directory>  
                <!--注意此次必须要放在此目录下才能被访问到-->  
                <targetPath>META-INF/resources</targetPath>  
                <includes>  
                    <include>**/**</include>  
                </includes>  
            </resource> 
     </resources> 
	</build>

注意指明maven的版本为1.4.2.RELEASE,否则jsp文件无法默认访问。


异常

sun.security.validator.ValidatorException:

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 


打包好后,发送至服务器,执行时出现证书错误,被坑了很久,IE浏览器似乎无法对url中的中文自动编码成url格式,所以一直以为自己证书没有安装,安装后仍无法访问,此时发现了IE浏览器url中的巨坑,开始怀疑是JDK的问题,将自己电脑上的JDK打包发送到服务器安装,安装成功后发现可以访问。


该异常一般解决方案如下:

点击打开链接


部署项目到服务器的教程

点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值