基于大数据的房价分析--4.用spring搭建后端接口

使用的是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);
    }
}
//地图action
package 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";
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值