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": "阴晴之间,谨防紫外线侵扰"
            }
        ]
    }
}


项目结构如下:

springboot实战——搭建天气查询网站_第1张图片


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 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 getweatherList(String city){
		if(json==null) 	{
			boolean judge = getjsondata(city);
			if(judge==false) return null; 
		}
		Vector result=new Vector();
		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 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所需要的信息)


	4.0.0

	com.example
	WeatheReporter-1
	0.0.1-SNAPSHOT
	jar

	WeatheReporter-1
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.1.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
      
            org.apache.tomcat.embed
            tomcat-embed-jasper
        

        
            org.eclipse.jdt.core.compiler
            ecj
            4.6.1
            provided
        
	
	
	
	weather
		
			
				org.springframework.boot
				spring-boot-maven-plugin
				1.4.2.RELEASE 
			
		
	      
              
              
                  
                src/main/webapp  
                  
                META-INF/resources  
                  
                    **/**  
                  
             
      
	


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"%>




Insert title here


<%
todayweather today=(todayweather)request.getAttribute("todayweather");
String error=(String)request.getAttribute("error");
Vector weatherset=(Vector)request.getAttribute("weather");
%>
<%
if(today!=null){
	out.print("

今日天气

"); out.print("温度:"+today.getWendu()); out.print("
"); out.print("湿度:"+today.getShidu()); out.print("
"); out.print("温馨提示:"+today.getGanmao()); out.print("
"); out.print("空气质量:"+today.getQuality()); out.print("
"); out.print("Pm2.5:"+today.getPm25()); out.print("
"); out.print("PM1.0:"+today.getPm10()); out.print("
"); } if(weatherset!=null){ int size=weatherset.size(); for(int i=0;i昨日天气"); else out.print("

天气展望

"); out.print("时间:"+weatherset.get(i).getDate()+"
"); out.print("日出:"+weatherset.get(i).getSunrise()+"
"); out.print("最高气温:"+weatherset.get(i).getSunrise()+"
"); out.print("最低气温:"+weatherset.get(i).getSunset()+"
"); out.print("aqi:"+weatherset.get(i).getAqi()+"
"); out.print("fx:"+weatherset.get(i).getFx()+"
"); out.print("fl:"+weatherset.get(i).getFl()+"
"); out.print("天气:"+weatherset.get(i).getType()+"
"); out.print("温馨提示:"+weatherset.get(i).getNotice()+"
"); } } if(error!=null){ out.print(error); } %>

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中添加如下语句:

	
	weather
		
			
				org.springframework.boot
				spring-boot-maven-plugin
				1.4.2.RELEASE 
			
		
	      
              
              
                  
                src/main/webapp  
                  
                META-INF/resources  
                  
                    **/**  
                  
             
      
	

注意指明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打包发送到服务器安装,安装成功后发现可以访问。


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

点击打开链接


部署项目到服务器的教程

点击打开链接

你可能感兴趣的:(java,EE)