maven SpringMVC 整合 mongoDB

<div class="iteye-blog-content-contain" style="font-size: 14px"></div>

 一.所有架包:

  <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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>springmongodb</groupId>
    <artifactId>springmongodb</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>springmongodb Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springversion>3.1.1.RELEASE</springversion>
        <junitversion>3.8.1</junitversion>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junitversion}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-asm</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${springversion}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-lgpl</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.5</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-lgpl</artifactId>
            <version>1.9.6</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>springmongodb</finalName>
    </build>
</project>
二.配置文件

    1.  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:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:cache="http://www.springframework.org/schema/cache"
        xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="
                    http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                    http://www.springframework.org/schema/tx
                    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                    http://www.springframework.org/schema/aop
                    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                    http://www.springframework.org/schema/context     
                    http://www.springframework.org/schema/context/spring-context-3.1.xsd
                    http://www.springframework.org/schema/cache
                    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
                    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd ">
                   
    <!-- 注解支持 -->
    <context:annotation-config />

    <!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 -->
    <context:component-scan base-package="com">
    </context:component-scan>
    <!-- 属性文件位置 -->
    <bean id="annotationPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:mongodb.properties</value>
            </list>
        </property>
    </bean>
    <!-- 实体映射 -->
    <bean id="packagesToScan" class="org.springframework.beans.factory.config.ListFactoryBean">
        <property name="sourceList">
            <list>
                <value>com.djh.user.entity</value>
            </list>
        </property>
    </bean>

    <!-- 注解式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
    </bean>

     <import resource="classpath:mongodb.xml"/>
     </beans>

   

   2.spring-mvc.xml

       <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-3.1.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <context:annotation-config />
    <!-- 使Spring支持自动检测组件,如注解的Controller -->
    <context:component-scan base-package="com.djh" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 启动 Spring MVC 的注解功能,完成请求和注解 POJO 的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

    <!-- 靜態資源訪問 -->
    <mvc:resources mapping="/js/**" location="/js/" />
    <mvc:annotation-driven />
    <bean    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>
</beans>

   3.mongodb.properties

    mongo.hostport=127.0.0.1:27017
    mongo.connectionsPerHost=8
   mongo.threadsAllowedToBlockForConnectionMultiplier=4
   #\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4
  mongo.connectTimeout=1000
  #\u7B49\u5F85\u65F6\u95F4
  mongo.maxWaitTime=1500
  mongo.autoConnectRetry=true
  mongo.socketKeepAlive=true
 #Socket\u8D85\u65F6\u65F6\u95F4
 mongo.socketTimeout=1500
  mongo.slaveOk=true

 

  4.mongodb.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" xsi:schemaLocation="http://www.springframework.org/schema/context  
          http://www.springframework.org/schema/context/spring-context-3.0.xsd  
          http://www.springframework.org/schema/data/mongo  
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd  
          http://www.springframework.org/schema/beans  
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- 加载mongodb的属性配置文件 -->
    <context:property-placeholder location="classpath:mongodb.properties" />

    <!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
    <mongo:mongo id="mongo" replica-set="${mongo.hostport}" host="${mongo.connectionsPerHost}">
        <!-- 一些连接属性的设置 -->
        <mongo:options
         threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
         connect-timeout="${mongo.connectTimeout}"
         max-wait-time="${mongo.maxWaitTime}"
         auto-connect-retry="${mongo.autoConnectRetry}"
         socket-keep-alive="${mongo.socketKeepAlive}"
         socket-timeout="${mongo.socketTimeout}"
         slave-ok="${mongo.slaveOk}"
         write-number="1"
         write-timeout="0"
         write-fsync="true" />
    </mongo:mongo>
    <!--  -->
    <mongo:db-factory dbname="djh" mongo-ref="mongo"  username="jack" password="123456"/>
      <!-- 自动扫描以下包的类 --> 
    <mongo:mapping-converter base-package="com.djh" />
   
     <bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
     
      <!-- 配置mongodb映射类型 --> 
    <bean id="mappingMongoConverter" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter"> 
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> 
        <constructor-arg name="mappingContext" ref="mappingContext" /> 
        <property name="typeMapper" ref="defaultMongoTypeMapper" /> 
    </bean>
    <!-- 默认Mongodb类型映射 --> 
    <bean id="defaultMongoTypeMapper" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper"> 
        <constructor-arg name="typeKey"> 
            <null /><!-- 这里设置为空,可以把 spring data mongodb 多余保存的_class字段去掉 --> 
        </constructor-arg> 
    </bean> 
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> 
         <constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
    </bean>
</beans>

 

5.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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <display-name>springmongodb</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>SpringDispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringDispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
</web-app>
   三所有配置已完成.连接访问

        1.实体类

 package com.djh.user.entity;
 
import java.io.Serializable;
 
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
 
@Document(collection="student")
public class Student implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 9088729114848434836L;
 
    private String  _id;
    private String name;
    private int age;
    private String bornDate;
 
    public String getName() {
        return name;
    }
    public String get_id() {
        return _id;
    }
 
    public void set_id(String _id) {
        this._id = _id;
    }
 
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getBornDate() {
        return bornDate;
    }
    public void setBornDate(String bornDate) {
        this.bornDate = bornDate;
//        org.springframework.data.mongodb.core.MongoTemplate
//        org.springframework.data.document.mongodb.MongoTemplate
       
    }
    
}

  2. 服务类(省略DAO类)

     package com.djh.user.serivce;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
 
import com.djh.user.entity.Student;
 
@Service
public class StudentService {
    @Autowired
    private MongoTemplate mongoTemplate;
 
    /**
     * 添加学生
     */
    public void add(Student stu) {
        mongoTemplate.insert(stu);
    }
 
    /**
     * 查所有学生
     * 
     * @return
     */
    public List<Student> findAllStudent() {
        return mongoTemplate.find(new Query(), Student.class);
    }
 
    /**
     * 根据Id查找学生
     */
    public Student findStudentById(String id) {
        return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)),
                Student.class);
 
    }
 
    /**
     * 根据id删除学生
     */
    public void delStudent(String id) {
        Criteria criteria = Criteria.where("_id").in(id);
        if (criteria != null) {
            Query query = new Query(criteria);
            if (query != null
                    && mongoTemplate.findOne(query, Student.class) != null)
                mongoTemplate.remove(mongoTemplate
                        .findOne(query, Student.class));
        }
    }
 
    /**
     * 修改
     * 
     * @param id
     */
    public void findAndModify(Student stu) {
        Query query = new Query(Criteria.where("_id").is(stu.get_id()));
        Update update = new Update();
        update.set("name", stu.getName());
        update.set("age",stu.getAge());
        update.set("bornDate", stu.getBornDate());
        mongoTemplate.updateFirst(query, update, Student.class);
    }
}

 3.controller类

    package com.djh.user.view;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 com.djh.user.entity.Student;
import com.djh.user.serivce.StudentService;

@Controller
@RequestMapping("/user")
public class StudentController {

    @Autowired
    private StudentService stuservice;

    @RequestMapping("/add")
    @ResponseBody
    public Map<String, Object> add(Student stu, String _id) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            stuservice.add(stu);
            map.put("flag", true);
        } catch (Exception e) {
            map.put("flag", false);
        }
        return map;
    }

    @RequestMapping("/viewAdd")
    public String viewAdd() {
        return "add";
    }

    @RequestMapping("/findAllStudent")
    public String findAllStudent(Map<String, Object> model) {
        List<Student> stus = stuservice.findAllStudent();
        model.put("students", stus);
        return "index";
    }

    /**
     * 根据_id查找学生
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/findById")
    public String findStudentByid(String _id, Map<String, Object> model) {
        Student stu = stuservice.findStudentById(_id);
        model.put("stu", stu);
        return "viewStudent";
    }

    /**
     * 根据_id删除
     */
    @RequestMapping("/delStudent")
    @ResponseBody
    public Map<String, Object> delStudent(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            stuservice.delStudent(id);
            map.put("flag", true);
        } catch (Exception e) {
            map.put("flag", false);
        }
        return map;
    }

    // 跳转修改页面
    @RequestMapping("/update")
    public String updateStudent(String id, Map<String, Object> model) {
        Student stu = stuservice.findStudentById(id);
        model.put("stu", stu);
        return "updateStudent";
    }

    /**
     * 修改学生
     *
     * @param stu
     * @return
     */
    @RequestMapping("/upStudent")
    @ResponseBody
    public Map<String, Object> upStudent(Student stu, String _id) {
        Map<String, Object> map = new HashMap<String, Object>();
        stu.set_id(_id);
        try {
            stuservice.findAndModify(stu);
            map.put("flag", true);
        } catch (Exception e) {
            map.put("flag", false);
        }
        return map;
    }
}

   本人在linux 下搭建  运行成功

   


你可能感兴趣的:(maven,mongodb,springMVC)