SpringMVC结合天气api实现天气查询
作者:Coder_py 发布时间:2021-06-01 16:56:41
标签:SpringMVC,api,天气查询
本实例实现在jsp页面实现查询全国城市天气预报的功能,供大家参考,具体内容如下
实例目录:
实现效果:
具体思路:
从和风天气api那里取得具体城市的api接口,获取json数据,再对json数据进行解析。
获取json数据:
package com.util;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NetUtilImpl implements NetUtil{
@Override
public String getJson(String url) throws IOException{
HttpURLConnection connection = null;
URL url2 = new URL(url);
connection=(HttpURLConnection) url2.openConnection();
/*对和风天气提供的链接进行连接*/
connection.connect();
/*获取状态码*/
int recode = connection.getResponseCode();
BufferedReader bufferedReader = null;
String json = new String();
/*如果连接成功*/
if(recode==200) {
/*对数据进行读,并且封装到json这个字符串,并且返回json*/
InputStream inputStream = connection.getInputStream();
bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
String string = null;
while ((string=bufferedReader.readLine())!=null) {
json=json+string;
ByteBuffer buffer = ByteBuffer.wrap(new String(string).getBytes("UTF-8"));
}
}
return json;
}
}
对json字符串进行解析,这里使用谷歌的gson工具包:
package com.util;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonUtilImpl implements JsonUtil{
@Override
public List<String> getData(String json) {
ArrayList<String> lists = new ArrayList<String>();
JsonParser jsonParser = new JsonParser();//json解析器
JsonObject object=(JsonObject) jsonParser.parse(json); //创建JsonObject对象
JsonArray array=object.get("results").getAsJsonArray();//得到json数组
JsonObject sJsonObject = array.get(0).getAsJsonObject();//按索引得到其中具体数据
JsonObject location = sJsonObject.get("location").getAsJsonObject();
JsonObject now = sJsonObject.get("now").getAsJsonObject();
lists.add(location.get("name").getAsString());
lists.add(now.get("text").getAsString());
lists.add(now.get("temperature").getAsString());
// lists.add(now.get("humidity").getAsString());
// lists.add(now.get("wind_speed").getAsString());
return lists;
}
}
完整代码:
Controller层:
package com.web;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.w3c.dom.ls.LSException;
import com.google.common.collect.Lists;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.util.JsonUtil;
import com.util.JsonUtilImpl;
import com.util.NetUtil;
import com.util.NetUtilImpl;
@Controller
@RequestMapping("/wea")
public class Forest {
NetUtilImpl netUtilImpl = new NetUtilImpl();
JsonUtilImpl jsonUtilImpl = new JsonUtilImpl();
@RequestMapping("/forest")
public String forest(String city,Model model) throws IOException {
String url = "https://api.seniverse.com/v3/weather/now.json?key=mtpmwyecaphmrzwc&location="+city+"&language=zh-Hans&unit=c";
String data = netUtilImpl.getJson(url);
List<String> lists = jsonUtilImpl.getData(data);
model.addAttribute("lists",lists);
return "display";
}
@RequestMapping("/fff")
public String fff() {
return "a";
}
}
springMVC配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 注解扫描包 -->
<context:component-scan base-package="com.web" />
<!-- 开启注解 -->
<mvc:annotation-driven />
<!-- 静态资源(js/image)的访问 -->
<mvc:resources location="/js/" mapping="/js/**"/>
<!-- 定义视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
查询主页:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" >
-->
</head>
<body>
<form action="/MyWeather/wea/forest">
city: <input type="text" name="city">
<input type="submit" value="提交">
</form>
</body>
</html>
展示页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'display.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" >
-->
</head>
<body>
<c:if test="${!empty lists }">
<c:forEach items="${lists}" var="lists">
<c:out value="${lists}"></c:out>
</c:forEach>
</c:if>
</body>
</html>


猜你喜欢
- StringBuilder与StringBuffer是两个常用的操作字符串的类。大家都知道,StringBuilder是线程不安全的,而St
- jvm虚拟机栈的作用jvm虚拟机栈栈帧的组成jvm虚拟机栈,也叫java栈,它由一个个的栈帧组成,而栈帖由以下几个部分组成局部变量表-存储方
- CompletableFuture 介绍CompletableFuture是1.8引入的新特性,一些比较复杂的异步计算场景,尤其是需要串联多
- 本文实例为大家分享了Android ViewPager实现页面左右切换的具体代码,供大家参考,具体内容如下主界面viewpager.xml:
- 面试题:1.如何保证多线程下 i++ 结果正确?2.一个线程如果出现了运行时异常会怎么样?3.一个线程运行时发生异常会怎样?为了避免临界区的
- @Validated和BindingResult 使用遇到的坑@Validated 与BindingResult 需要相邻,否则 变量res
- 前言春节要到了,看惯了前端各种小游戏,确实做得很好,很精致。但是我也要为后端程序员稍微做一点贡献,做一款java版本的【年兽大作战】。这个游
- 前言《接月饼小游戏》是一个基于java的自制游戏,不要被月亮砸到,尽可能地多接月饼。此小项目可用来巩固JAVA基础语法,swing的技巧用法
- 在移动支付领域,支付宝支付占用巨大份额,根据艾瑞咨询公布的报告数据:2014Q3,支付宝斩
- Android中ListView下拉刷新实现效果图:ListView中的下拉刷新是非常常见的,也是经常使用的,看到有很多同学想要,那我就整理
- 1. 首先设置Web视图webview.setWebViewClient(new MyWebViewClient());webview1.s
- 在android 6.0开始,部分的权限需要我们动态申请,也就是说当我们的打开app的时候系统不会主动像您申请app所需要的部分权限,需要客
- 介绍本篇给大家带了的是ViewFlipper,它是Android自带的一个多页面管理控件,且可以自动播放! 和ViewPager不同,Vie
- 运算符重载一直是一个很诡异事情,因为在写代码的时候,不知道某个运算符有没有被重载过。在 C++ 里面,运算符重载可以写在类的外面,当 int
- 本文实例为大家分享了java实现猜字母游戏的具体代码,供大家参考,具体内容如下案例需求:StepOne:系统随机生成一组随机的字符数组(不重
- Java流程控制用户交互Scannerjava.util.Scanner是Java5的新特征,可以通过Scanner类来获取用户的输入基本语
- java 值Document解析xml详细介绍使用jar包:jdom.jar配置文件格式 global.xml一、获取输入的值组成的结点我们
- 本文实例分析了C#实现的24点游戏。分享给大家供大家参考。具体如下:1. 24点游戏规则及算法规则:给出4个自然数,找出能够求出24的四则运
- 帮我们实现各种类型的复杂手势操作。其实例通过静态工厂创建ViewDragHelper一般用在一个自定义ViewGroup的内部。初始化操作
- mybatis-plus返回查询总记录数mp框架提供了selectCount方法,来查询总记录数;需求:查找薪水大于3500 名字里有&am