基于大数据的房价分析--4.用spring搭建后端接口
来源:互联网 发布:网络基础知识入门 视频 编辑:程序博客网 时间:2024/04/26 08:08
使用的是springMVC框架,目前功能实现的非常简陋,大家做个参考就可以了
1.搭建一个maven项目
我使用的是idea,直接搭建一个maven项目
在pom.xml中加入如下依赖
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!--spring框架--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--springMVC框架--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--springMVC框架--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--mongodb驱动--> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.6.0</version> </dependency> <!--构建json数据的依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency> <!--httpclient的依赖,暂时不需要--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.4</version> </dependency> </dependencies>
需要将resource目录指定为resource目录,这样,将配置文件放置在该目录下会自动复制到你设置的类输出目录中,否则使用”classpath”时会找不到配置文件
2.基本配置文件编写
1.web.xml配置文件编写
<!--前端控制器配置--><servlet> <!--指定该控制器的类--> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!--指定该控制器的配置文件--> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <!--指定该控制器拦截路径--> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--指定上下文配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
需要理解的是classpath指的是编译java代码的输出路径
2.springmvc配置文件编写
<!--开启注解--> <mvc:annotation-driven/> <!--开启组件扫描--> <content:component-scan base-package="Test,Utils,Dao,Service,Action"></content:component-scan> <mvc:resources mapping="**/Plug-in/**" location="Plug-in"></mvc:resources> <mvc:resources mapping="**/Image/**" location="Image"></mvc:resources> <!--拦截器用于指定首页--> <mvc:interceptors> <!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 --> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/index.do"/> <!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 --> <bean class="Interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors> <!--视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/View/"/> <property name="suffix" value=".jsp"/> </bean> <!--配置文件解析器--> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/config/mongoconfig.properties</value> </list> </property> </bean>
3.代码
1.dao
//dao接口package Dao;import java.util.List;import java.util.Map;public interface BaseDao { public List executeQuery(Map<String,Object> condition, String dbname, String collname,int number,int isDataLimit); public void executeAdd(Map<String,Object> condition,String dbname,String collname); public void executeUpdate(Map<String,Object> condition,String dbname,String collname); public void executeRemove(Map<String,Object> condition,String dbname,String collname);}
//dao实现package Dao;import Beans.Location;import Utils.DumpClassUtil;import Utils.MongoUtil;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoCollection;import org.bson.Document;import org.springframework.stereotype.Component;import javax.annotation.Resource;import java.util.ArrayList;import java.util.List;import java.util.Map;@Component("cityMapDao")public class CityMaoDao implements BaseDao { @Resource(name = "mongoUtil") private MongoUtil mongoUtil; public List executeQuery(Map<String,Object> condition, String dbname, String collname,int number,int isDataLimit) { List result = new ArrayList(); MongoCollection collection = mongoUtil.getClient().getDatabase(dbname).getCollection(collname); FindIterable<Document> documents = null; if(isDataLimit == 1) { if(condition != null) documents = collection.find(new Document(condition)).limit(number); else documents = collection.find().limit(number); }else{ if(condition != null) documents = collection.find(new Document(condition)); else documents = collection.find(); } for(Document document:documents){ Location loc = DumpClassUtil.dumpLocation(document); if(loc != null) { result.add(loc); } } return result; } public void executeAdd(Map<String,Object> condition,String dbname,String collname) { } public void executeUpdate(Map<String,Object> condition,String dbname,String collname) { } public void executeRemove(Map<String,Object> condition,String dbname,String collname) { }}
2.service
//service接口package Service;import Dao.BaseDao;import java.util.Map;public interface BaseService { public Object service(Map<String,Object> map, String dbName,String colName,int Number,int isDataLimit);}
//service实现package Service;import Dao.BaseDao;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import org.springframework.stereotype.Controller;import javax.annotation.Resource;import java.util.Map;@Component("cityService")public class CityService implements BaseService { @Resource(name = "cityMapDao") private BaseDao dao; public Object service(Map<String,Object> map, String dbName,String colName,int number,int isDataLimit) { return dao.executeQuery(map,dbName,colName,number,isDataLimit); }}
3.bean类
package Beans;import java.util.Date;public class Location { private String detailUrl; private String address; private Float size; private String orient; private String roomNum; public void setDetailUrl(String detailUrl) { this.detailUrl = detailUrl; } public void setAddress(String address) { this.address = address; } public void setSize(Float size) { this.size = size; } public void setOrient(String orient) { this.orient = orient; } public void setRoomNum(String rooomNum) { this.roomNum = rooomNum; } public void setUnitPrice(Float unitPrice) { this.unitPrice = unitPrice; } public void setSumPrice(Float sumPrice) { this.sumPrice = sumPrice; } public void setLn(Double ln) { this.ln = ln; } public void setLat(Double lat) { this.lat = lat; } public void setTime(Date time) { this.time = time; } public void setCity(String city) { this.city = city; } public String getDetailUrl() { return detailUrl; } public String getAddress() { return address; } public Float getSize() { return size; } public String getOrient() { return orient; } public String getRoomNum() { return roomNum; } public Float getUnitPrice() { return unitPrice; } public Float getSumPrice() { return sumPrice; } public Double getLn() { return ln; } public Double getLat() { return lat; } public Date getTime() { return time; } public String getCity() { return city; } public String print(){ return "address:"+this.getAddress()+ "Size:"+this.getSize()+ "orient:"+this.getOrient()+ "detailUrl:"+this.getDetailUrl()+ "unitPrice:"+this.getUnitPrice()+ "sumPrice:"+this.getSumPrice()+ "RooomNum:"+this.getRoomNum()+ "Ln:"+this.getLn()+ "Lat:"+this.getLat()+ "Time:"+this.getTime(); } private Float unitPrice; private Float sumPrice; private Double ln; private Double lat; private Date time; private String city;}
4.用于封装bean的util类
package Utils;import org.bson.Document;import Beans.Location;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DumpClassUtil { public static Location dumpLocation(Document doc){ Location location = new Location(); if(doc.containsKey("address")){ location.setAddress(doc.getString("address")); } if(doc.containsKey("city")){ location.setCity(doc.getString("city")); } if(doc.containsKey("roomNum")){ location.setRoomNum(doc.getString("roomNum")); } if(doc.containsKey("orient")){ location.setOrient(doc.getString("orient")); } if(doc.containsKey("size")){ try { Float size = Float.parseFloat(doc.getString("size")); location.setSize(size); }catch (Exception e){ return null; } } if(doc.containsKey("unitPrice")){ try { Float unitPrice = Float.parseFloat(doc.getString("unitPrice")); location.setUnitPrice(unitPrice); }catch(Exception e){ return null; } } if(doc.containsKey("sumPrice")){ try { Float sumPrice = Float.parseFloat(doc.getString("sumPrice")); location.setSumPrice(sumPrice); }catch(Exception e){ return null; } } if(doc.containsKey("ln")){ Double ln = doc.getDouble("ln"); location.setLn(ln); } if(doc.containsKey("lat")){ Double lat = doc.getDouble("lat"); location.setLat(lat); } if(doc.containsKey("time")){ Double dateDouble = doc.getDouble("time"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try{ String dateString=format.format(dateDouble); Date date = format.parse(dateString); location.setTime(date); }catch (ParseException e){ e.printStackTrace(); location.setTime(null); } } return location; }}
5.用于获得数据库连接的util类
package Utils;import com.mongodb.MongoClient;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Component("mongoUtil")public class MongoUtil { private static MongoClient client; @Value("${ip}") private String IP; @Value("${port}") private String PORT; public MongoClient getClient(){ if (this.client == null) { this.client = new MongoClient(this.IP, Integer.parseInt(this.PORT)); } return client; } public void closeClient(){ this.client.close(); this.client = null; }}
action
//action最初的父类package Action;import Service.BaseService;import com.alibaba.fastjson.JSON;import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.List;import java.util.Map;import java.util.TreeMap;public class BaseAction { protected BaseService service; protected String dbName; protected String colName; @ResponseBody public String datas(HttpServletRequest request, HttpServletResponse response){ String city = (String)request.getParameter("city"); Integer number = Integer.parseInt((String)request.getParameter("number")); int isdatalimit = Integer.parseInt((String)request.getParameter("isDataLimit")); Map<String,Object> query = new TreeMap<String,Object>(); if(city != null) { query.put("city", city); }else{ query = null; } List list = (List)this.service.service(query,this.dbName,this.colName,number,isdatalimit); return JSON.toJSONString(list); }}
//地图actionpackage Action.house;import Action.BaseAction;import Service.BaseService;import com.alibaba.fastjson.JSON;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.List;import java.util.Map;import java.util.TreeMap;/** * Created by JACK on 2017/12/8. */@Controller@RequestMapping(value = "/house")public class CityMapAction extends BaseAction { @Resource(name = "cityService") private void setService(BaseService service){ this.service = service; } @Value("${locationDB}") private void setDBName(String dbName){ this.dbName = dbName; } @Value("${locationCol}") private void setColName(String colName){ this.colName = colName; } @RequestMapping(value = "map.do",produces = "text/json;charset=UTF-8") public String map(HttpServletRequest request, HttpServletResponse response){ return "house/map"; } @RequestMapping(value = "datas.do",produces = "text/json;charset=UTF-8") @ResponseBody public String getDatas(HttpServletRequest request, HttpServletResponse response){ return this.datas(request,response); } @RequestMapping(value = "index.do",produces = "text/json;charset=UTF-8") public String index(HttpServletRequest request, HttpServletResponse response){ return "house/index"; }}
阅读全文
0 0
- 基于大数据的房价分析--4.用spring搭建后端接口
- 基于大数据的房价分析
- 基于大数据的房价分析--1.数据爬取
- 基于大数据的房价分析--2.数据解析
- 基于大数据的房价分析--3.echart+百度地图实现数据可视化
- 如何利用大数据分析一个城市的房价
- 大数据分析平台搭建教程:基于Apache Zeppelin Notebook和R的交互式数据科学
- 大数据分析平台搭建教程:基于Apache Zeppelin Notebook和R的交互式数据科学
- 基于mdrill的大数据分析
- 基于mdrill的大数据分析
- 基于大数据的中文舆情分析
- 大数据分析- 基于Hadoop/Mahout的大数据挖掘
- 大数据分析- 基于Hadoop/Mahout的大数据挖掘
- 大数据分析- 基于Hadoop/Mahout的大数据挖掘
- 大数据分析- 基于Hadoop/Mahout的大数据挖掘
- 大数据分析- 基于Hadoop/Mahout的大数据挖掘
- 查询房价具体信息的接口(基于flask)
- spring基于xml格式的前后端数据交换的配置 之 MarshallingHttpMessageConverter + xstream
- ==,is,isinstance的区别(Python)
- Android多线程之IntentService
- Python简单爬虫实现
- eclipse jsp报错 superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
- vue element-ui table表格滚动加载
- 基于大数据的房价分析--4.用spring搭建后端接口
- 数据结构期末总结
- Citypicker省市区地址选择器3.0.0版本发布,重大更新!!!
- 最新升级Android Studio3.0及Android Studio3.1,输入法输入中文,卡顿,出不来提示的情况终极解决方案
- Git操作详解
- 第十四周项目一
- Java图片上传+回显技术
- 室内也能用 那些适合在跑步机上使用的可穿戴设备
- JAVA 解析XML文件