MongoDB实现商品评论

MongoDB实现商品评论

一、从MongoDB获取商品评论信息
  1. MongoDB配置文件:mongo.properties
host=127.0.0.1
port=27017
databaseName=zhiheng
collectionName=discuss
  1. MongoDBUtil工具类
package com.java.web.util;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MongoUtil {
    private static MongoCollection<Document> userCollection=null;
    private static MongoClient client = null;
    private static String host = null;
    private static Integer port = null;
    private static String databaseName = null;
    private static String collectionName = null;

    static{
        try {
            //1、创建Properties对象来表示mongo.properties文件
            Properties prop = new Properties();
            //2、关联
            InputStream ins = MongoUtil.class.getClassLoader().getResourceAsStream("mongo.properties");
            prop.load(ins);
            //3、获取文件中的数据
            host = prop.getProperty("host");
            port = Integer.parseInt(prop.getProperty("port")) ;
            databaseName = prop.getProperty("databaseName");
            collectionName = prop.getProperty("collectionName");
            //4、关流
            ins.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取集合
     * @return
     */
    public static MongoCollection<Document> getCollection(){
        //1、连接上MongoDB
        client = new MongoClient(host,port);
        //2、连接上指定的库
        MongoDatabase db = client.getDatabase(databaseName);
        //3、连上指定的集合
        userCollection = db.getCollection(collectionName);
        return userCollection;
    }

    /**
     * 关闭MongoDB的客户端
     */
    public static void close(){
        if(client!=null)
            client.close();
    }
}
  1. 评论业务层接口
package com.java.web.service;

import org.bson.Document;
import java.util.List;

/**
 * 评论业务层接口
 */
public interface DiscussService {
    // 查询所有评论数据
    List<Document> findPageDiscuss(Integer page,Integer limit)throws Exception;
}
  1. 评论业务层实现类
package com.java.web.service.impl;

import com.java.web.service.DiscussService;
import com.java.web.util.MongoUtil;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Liushun
 * @date Created in 2018/8/22 9:35
 * @description 评论的业务层实现类
 */
@Service
@Transactional(readOnly = false)
public class DiscussServiceImpl implements DiscussService {

    @Override
    public List<Document> findPageDiscuss(Integer page, Integer limit) throws Exception {
        MongoCollection<Document> discussCollection = MongoUtil.getCollection();
        // 执行数据查询
        FindIterable<Document> documents = discussCollection.find();
        // 进行分页查询
        documents.skip((page - 1) * limit).limit(limit);
        // 新建一个list集合
        ArrayList<Document> list = new ArrayList<>();
        // 将查询的数据进行遍历输出,在加入到list集合中
        documents.iterator().forEachRemaining(temp-> System.out.println(list.add(temp)));

        return list;
    }
}
  1. 评论控制器层
package com.java.web.controller;

import com.java.web.service.DiscussService;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author Liushun
 * @date Created in 2018/8/22 9:47
 * @description 评论的控制器
 */
@Controller
@RequestMapping("/discuss")
public class DiscussController {

    @Autowired
    private DiscussService discussService;

    @RequestMapping("/loadPageDiscuss")
    public @ResponseBody List<Document> loadPageDiscuss(Integer page,Integer limit){
        try {
            return discussService.findPageDiscuss(page,limit);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
二、使用过滤器工具解决跨域问题
  1. 过滤器工具
package com.java.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * description:
 * author:Liushun
 * date:10:13
 */
@WebFilter(urlPatterns = {"/*"})  //请求的路径
public class KuayuFilter implements Filter{
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("KuayuFilter初始化成功了。。。"); // 测试用
    }

    @Override
    public void doFilter(ServletRequest res, ServletResponse req, FilterChain chain) throws IOException, ServletException {
        System.out.println("KuayuFilter执行了。。。");    // 测试用
        HttpServletRequest request = (HttpServletRequest) res;
        HttpServletResponse response=(HttpServletResponse)req;
        //允许跨域访问
        response.setHeader("Access-Control-Allow-Origin", "*"); // 设置允许所有跨域访问
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //放行
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        System.out.println("KuayuFilter销毁了。。。");    // 测试用
    }
}
  1. WebStart启动器添加注解使跨域工具生效
@ServletComponentScan(basePackages = "com.java.web.filter")
三、将商品评论信息整合到显示页面
  1. Product.ftl 模板
<script type="text/javascript">
    jQuery(function () {
        jQuery("#p_comment").click(function () {	// p_comment为商品评论id
            jQuery.ajax({
                type:'GET',
                url:'http://localhost:8083/discuss/loadPageDiscuss',
                dataType:'JSON',
                data:{"page":1,"limit":3},
                success:function (data) {
                    var content = "";
                    for(var i in data){
                        content+="<tr valign=\"top\">\n" +
                                "<td width=\"160\"><img src='"+data[i].userImg+"' width=\"20\" height=\"20\" align=\"absmiddle\" />&nbsp;"+data[i].userName+"</td>\n" +
                                "<td width=\"180\">\n" +
                                "\t颜色分类:<font color=\"#999999\">"+data[i].color+"</font> <br />\n" +
                                "\t型号:<font color=\"#999999\">"+data[i].type+"</font>\n" +
                                "</td>\n" +
                                "<td>\n" +
                                "\t"+data[i].content+"<br />\n" +
                                "\t<font color=\"#999999\">"+data[i].dateTime+"</font>\n" +
                                "</td>\n" +
                                "</tr>"
                    }
                    jQuery(".jud_list").html(content);	// jud_list为商品评论表格的class属性
                },
                error:function (data) {
                    alert("服务器异常")
                }
            })
        })
    })
</script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值