SpringMVC+Mongo简单配置

Ps:我使用的是Eclipse+Maven

 
首先新建工程
将其转化为maven
可以使用Eclipse自带的填入spring需要的jar包
找到mongo的依赖添加进去就行了
这是添加完毕后的pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.feng</groupId>
  <artifactId>SpringMongo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>SpringMongo</name>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>4.2.3.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>4.2.3.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>4.2.3.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>4.2.3.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.2.3.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
          <version>1.2</version>
      </dependency>
      <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.8.2.RELEASE</version>
    </dependency>
  </dependencies>
</project>

 

然后配置spring
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
            <!-- 识图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/view/"></property>
        <property name="suffix" value=".jsp"></property>

    </bean>

</beans>

applicationContext.xml

<?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:mongo="http://www.springframework.org/schema/data/mongo"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.8.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

        <mvc:annotation-driven></mvc:annotation-driven>
    
    <!-- 扫描注解的目录 -->
    <context:component-scan base-package="com.feng.controller"></context:component-scan>
    
<!--     这一种可以指定数据库的ip和端口
    <mongo:mongo id="mongoDB" host="127.0.0.1" port="27017"></mongo:mongo>
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref=“mongoDB" />
        <constructor-arg value=“test" />  数据库的名称 
        <property name="writeConcern" value="SAFE" />
    </bean> -->
    
    
    <!-- 默认访问127.0.0.1:27017 -->
    <mongo:db-factory id="mongoDbFactory" dbname="test"/>
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongoDbFactory" />
        <property name="writeConcern" value="SAFE" />
    </bean>
    
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringMongo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
<!-- 配置拦截器,然后需要springmvc的配置文件 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- 配置拦截器,拦截所有.action的请求 -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    
    <!-- 加载spring的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  
</web-app>

 


然后我有新建了个测试的类
package com.feng.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

@Controller
@RequestMapping("/")
public class Test {
    
    @Autowired
    private MongoTemplate mt; //自动注入MongoTemplate
    
    @RequestMapping("/index")
    public String index(){
        
        return "index";
    }
    
}

 


这是我的index.jsp,放在了WEB-INF/view目录下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<h1>index</h1>
 
</body>
</html>
首先测试获取所有数据,在test类中这样写
        DBCollection db = mt.getCollection("user"); //获取test数据库里面的user这个collection

        DBCursor dc = db.find();
        
        while (dc.hasNext()) {
            DBObject obj = dc.next();
            
            System.out.println(obj);
        }
然后访问http://localhost:8080/SpringMongo/index.action,自动跳转到index.jsp
控制台输出所有数据(我之前测试Mongo时乱填的)
 
{ "_id" : { "$oid" : "56aba53174a5c31c6a1be2b7"} , "name" : "feng" , "address" : { "street" : "2 Avenue" , "zipcode" : "10075" , "building" : "1480" , "coord" : [ -73.9557413 , 40.7720266]}}
{ "_id" : { "$oid" : "56ac73bc945e7d0dc812d9ba"} , "family" : { "one" : "BOB"}}
{ "_id" : { "$oid" : "56ac73cf945e7d28f4788954"} , "name" : "hua" , "family" : { "one" : "BOB" , "two" : "Bob" , "three" : "Jack"} , "phone" : "123456"}
{ "_id" : { "$oid" : "56ac790c945e7d030886611b"} , "name" : "hua" , "family" : { "one" : "nick" , "two" : "Bob" , "three" : "Jack"} , "phone" : "123456"}
测试条件查询,这是需要用到DBObject以及他的实现类BasicDBObject,参见http://api.mongodb.org/java/2.3/com/mongodb/BasicDBObject.html
这个相当于MongoDB中的Document类,而且用法完全相同,这里可以参考https://docs.mongodb.org/getting-started/java/query/ mongo官方给的一些教程(增删改查都相似),我只给出一个查询和更改的例程
部分代码
DBObject dbo = new BasicDBObject();
dbo.put("name", "feng"); //放入你要查询的条件
 
DBCursor dc = db.find(dbo);    //也可以db.find(new BasicDBObject().append(key,val));
//然后输出dc即可

 

然后说一下更新db.update(DBObject q, DBObject o),q是查询条件,o是更新的内容,update仅更新查询到的第一条数据,多条的话请使用updateMulti();
WriteResult wr = db.update(new BasicDBObject().append("name", "hua"), new BasicDBObject().append("$set",new BasicDBObject().append("family.one", "BOB")));//这一种是仅更新family.one这一个字段
db.update(new BasicDBObject().append("name", "a"), new BasicDBObject().append("name", "nihao").append("phone", "123456"));
//这一种相当于替换,比如原来的数据是{"name":"a","address":"china"}执行后变成了{"name":"nihao","phone":"123456"}

 

剩下的都很简单,就不再赘述了。
posted @ 2016-02-01 20:47  山里的小房子  阅读(3079)  评论(0编辑  收藏  举报