Java连接MongoDB进行增删改查

1.导入必须的包:

   详情看项目:http://pan.baidu.com/s/1cvDAOY

2.通过Myeclipse创建WEB项目

3.

3.bean:创建实体类

package com.bean;

import java.io.Serializable;
import java.util.Date;
/**
 * @since 对应于mongodb中的数据库test中的表com
 * @author think
 *
 */
public class Company implements Serializable {
    private static final long serialVersionUID = 4379611409753357157L;

    private String id;
    private String companyName;
    private String url;
    private String ip;
    private Date createTime;
    private Date updateTime;

    public Company() {
    }

    public Company(String id, String companyName, String url, String ip,
            Date createTime, Date updateTime) {
        super();
        this.id = id;
        this.companyName = companyName;
        this.url = url;
        this.ip = ip;
        this.createTime = createTime;
        this.updateTime = updateTime;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

}

4.创建工具类,主要是获取本机的ip地址

package com.common;

import javax.servlet.http.HttpServletRequest;

public class Util {

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || "".equals(ip) || ip.length() == 0
                || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || "".equals(ip) || ip.length() == 0
                || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || "".equals(ip) || ip.length() == 0
                || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;

    }
}

5.创建:控制器类(通过控制器来执行不同的操作)

package com.controller;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.bean.Company;
import com.service.ICompany;
@Controller
@RequestMapping("/company")
public class CompanyController {
    private static Log log = LogFactory.getLog(CompanyController.class
            .getName());
    @Autowired
    private ICompany icompany;

    // 查询所有公司
    @RequestMapping("/companys")
    public ModelAndView companys() {
        List<Company> list = icompany.findCompanys();
        ModelAndView mdl = new ModelAndView();
        mdl.setViewName("/companys");
        mdl.addObject("user", list);
        return mdl;
    }
    //更新
    @RequestMapping("/toUpdateCompany")
    public ModelAndView toUpdateCompany(@RequestParam("id")String id){
        ModelAndView mdl=new ModelAndView();
        mdl.setViewName("/company_update");
        Company company=icompany.findCompany(id);
        mdl.addObject("company", company);
        return mdl;
    }
    //更新保存
    @RequestMapping("/updateCompany")
    public String update(@ModelAttribute Company company){
        try {
            company.setUpdateTime(new Date());
            icompany.updateCompany(company);
        } catch (Exception e) {
            log.error(e);
        }
        return companyList();
    }
    private String companyList() {
        return "redirect:/company/companys.action";
    }
    //删除
    @RequestMapping("/delCompany") 
    public String delCompany(@RequestParam("id") String id){
        icompany.delCompany(id);
        return companyList();
    }
    //增加
    @RequestMapping("/toAddCompany")
    public ModelAndView addCompany(){
        return returnUrl("/company_add");
    }
    private ModelAndView returnUrl(String url) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName(url);
        return mav;
        
    }
    //增加到数据库
    @RequestMapping("/addCompany")
    public String add(@ModelAttribute Company company){
        company.setCreateTime(new Date());
        company.setUpdateTime(new Date());
        icompany.addCompany(company);
        return companyList();
    }
}

(登陆验证,在实际过程中要在数据库中匹配验证)

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.sun.org.apache.commons.logging.Log;
import com.sun.org.apache.commons.logging.LogFactory;

@Controller
@RequestMapping("/sys")
public class SysController {
    private static Log log = LogFactory.getLog(SysController.class.getName());

    @RequestMapping("/login")
    public String Login(@RequestParam("userName") String userName,@RequestParam("userPwd") String userPwd) {
        try {
            if ("admin".equals(userName) && "123456".equals(userPwd)) {
                return "redirect:/company/companys.action";
            }
        } catch (Exception e) {
            log.error(e);
        }
        return "redirect:/index.jsp";
    }

    @RequestMapping("/welcome")
    public String welcome() {
        return "redirect:/index.jsp";
    }
}

6.创建数据库的连接,进行增删改查

(分别为接口和实现类)

package com.dao;

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.stereotype.Repository;

import com.bean.Company;

@Repository
public class RepositoryImpl implements AbstractRepository {
    @Autowired
    private MongoTemplate mongoTemplate;

    // 查询所有数据
    public List<?> findAll(Class<?> entity) {
        return mongoTemplate.findAll(entity);
    }

    // 更新数据
    public Company findOne(String id, Class<?> entity) {
        return (Company) mongoTemplate.findOne(new Query(Criteria.where("id")
                .is(id)), entity);

    }

    // 添加到数据库
    public void updateEntity(Company company) {
        mongoTemplate.save(company);
    }

    // 删除选中的数据
    public void delete(String id, Class<Company> class1) {
        Criteria criteria = Criteria.where("id").in(id);
        if (criteria != null) {
            Query query = new Query(criteria);
            if (query != null && mongoTemplate.findOne(query, class1) != null)
                mongoTemplate.remove(mongoTemplate.findOne(query, class1));
        }

    }
    //增加到数据库
    public void insert(Company company) {
        mongoTemplate.insert(company);
        
    }

}
package com.dao;

import java.util.List;

import com.bean.Company;

public interface AbstractRepository {
    public List<?> findAll(Class<?> entity);
    
    public Company findOne(String id,Class<?> entity);

    public void updateEntity(Company company);

    public void delete(String id, Class<Company> class1);

    public void insert(Company company);
}

7.创建service类,对业务进行处理

package com.service;

import java.util.List;

import com.bean.Company;

public interface ICompany {

    /**
     * 查询所有公司
     */
    public List<Company> findCompanys();
    /**
     * 更新数据
     * @param id
     * @return
     */
    public Company findCompany(String id);
    //更新到数据库
    
    public void updateCompany(Company company);
    //删除选中的数据
    public void delCompany(String id);
    //增加
    public void addCompany(Company company);
}
package com.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bean.Company;
import com.dao.AbstractRepository;
@Service
public class CompanyImpl implements ICompany {
    @Autowired
    private AbstractRepository dao;
    public List<Company> findCompanys() {
        List<Company> list=(List<Company>) dao.findAll(Company.class);
        return list;
    }
    //更新数据
    public Company findCompany(String id) {
       return dao.findOne(id, Company.class);
    }
    public void updateCompany(Company company) {
        dao.updateEntity(company);
    }
    //删除选中的数据
    public void delCompany(String id) {
        dao.delete(id,Company.class);
    }
    //增加到数据哭
    public void addCompany(Company company) {
        dao.insert(company);
    }

}

8.配置对应的配置文件(applicationContext.xml--spring配置(依赖注入),dispatcher-servlet.xml(mongodb数据库的配置))

<?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.3.xsd  
              http://www.springframework.org/schema/beans  
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <context:property-placeholder location="classpath:mongodb.properties" />
    <!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
    <mongo:mongo id="mongo" replica-set="127.0.0.1:27017">
        <mongo:options connections-per-host="${mongo.connectionsPerHost}"
            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}" write-number="1"
            write-timeout="0" write-fsync="true" />
        <!--<mongo:options connections-per-host="${mongo.connectionsPerHost}" 每个主机答应的连接数(每个主机的连接池大小),当连接池被用光时,会被阻塞住 
            ,默以为10 threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" 
            connect-timeout="${mongo.connectTimeout}" 在建立(打开)套接字连接时的超时时间(ms) max-wait-time="${mongo.maxWaitTime}" 
            被阻塞线程从连接池获取连接的最长等待时间 auto-connect-retry="${mongo.autoConnectRetry}" 控制系统在发生连接错误时是否重试 
            ,默以为false boolean socket-keep-alive="${mongo.socketKeepAlive}" 这个控制是打开(SO_KEEPALIVE)。默认值为false,布尔 
            socket-timeout="${mongo.socketTimeout}" #套接字超时时间;该值会被传递给Socket.setSoTimeout(int)。默以为0(无穷) 
            write-number="1" write-timeout="0" safe="false" #假如为true,驱动每次update后会发出一个getLastError命令来保证成功,默以为false 
            write-fsync="true"/> -->
    </mongo:mongo>
    <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
    <mongo:db-factory dbname="test" mongo-ref="mongo" />
    <!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"></constructor-arg>
    </bean>

</beans>
<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!-- 使Spring支持自动检测组件,如注解的Controller -->
    <mvc:annotation-driven />
    <context:annotation-config />
    <context:component-scan base-package="com" />
    <!-- 视频解析 -->
    <bean
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></property>
    </bean>
</beans>

9.log4j与数据库参数的配置

log4j.rootLogger=INFO,CONSOLE
log4j.category.com=DEBUG,messageWEB

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS}[%C]-[%p] %m%n

log4j.appender.messageWEB=org.apache.log4j.DailyRollingFileAppender
log4j.appender.messageWEB.File=F\:\\logsdaily_rolling.log
log4j.appender.messageWEB.DatePattern=.yyyy-MM-dd
log4j.appender.messageWEB.layout=org.apache.log4j.PatternLayout
log4j.appender.messageWEB.layout.ConversionParttern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n
log4j.appender.messageWEB.Encoding=UTF-8
mongo.connectionsPerHost=4
mongo.threadsAllowedToBlockForConnectionMultiplier=20
mongo.connectTimeout=0
mongo.maxWaitTime=10000
mongo.autoConnectRetry=true
mongo.socketKeepAlive=true
mongo.socketTimeout=0

10---前端展示--jsp文件

company_add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>客户验证平台</title>
</head>
<body>
<p align="left"><font size="7">客户添加</font></p>
<form action="<%=path%>/company/addCompany.action" method="post">
<p>客户名称:<input type="text" name="companyName" value=""/></p>
<p>客户网址:<input type="text" name="url" value=""/></p>
<p>客户ip:<input type="text" name="ip" value=""/></p>
<p><input type="submit" value="保存"/></p>
</form>
</body>
</html>
company_update.jsp
<
%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>客户验证平台</title> </head> <body> <p align="left"><font size="7">客户修改</font></p> <form action="<%=path%>/company/updateCompany.action" method="post"> <input type="hidden" name="id" value="${company.id}"/> <input type="hidden" name="createTime" value="${company.createTime}"/> <p>客户名称:<input type="text" name="companyName" value="${company.companyName}"/></p> <p>客户网址:<input type="text" name="url" value="${company.url}"/></p> <p>客户ip:<input type="text" name="ip" value="${company.ip}"/></p> <p><input type="submit" value="保存"/></p> </form> </body> </html>

companys.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>客户验证平台</title>
    </head>
    <body>
        <p align="left">
            <font size="7">客户列表</font>
        </p>
        <table border="1">
            <tr>
                <td>id</td>
                <td>客户名称</td>
                <td>客户网址</td>
                <td>客户ip</td>
                <td>创建时间</td>
                <td>最后修改时间</td>
                <td>操作</td>
            </tr>
            <c:forEach items="${user}" var="user">
            <tr>
                <td>${user.id}</td>
                <td>${user.companyName }</td>
                <td>${user.url }</td>
                <td>${user.ip }</td>
                <td><fmt:formatDate value="${user.createTime}"></fmt:formatDate></td>
                <td><fmt:formatDate value="${user.updateTime }"/></td>
                <td>
                   <a href="<%=path%>/company/toUpdateCompany.action?id=${user.id}">修改</a>
                   <a href="<%=path%>/company/delCompany.action?id=${user.id}">删除</a>
                   <a href="<%=path%>/company/toAddCompany.action">添加</a>
                </td>
            </tr>
            </c:forEach>
        </table>
    </body>
</html>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>客户验证平台</title>
    </head>
    <body>
        <p align="center">
            <font size="7">客户验证平台</font>
        </p>
        <form action="<%=path%>/sys/login.action" method="post">
            <p align="center">
                用户名:
                <input type="text" name="userName" />
                &nbsp;&nbsp; 密码:
                <input type="password" name="userPwd" />
                <input type="submit" value="登录" />
            </p>
        </form>
    </body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name></display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <description>加载目录下的所有XML作为Spring MVC的配置文件</description>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    <!-- WEB项目中的上下文 -->
    <context-param>
        <description></description>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <description>监听器</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <error-page>
        <error-code>404</error-code>
        <location>/404.html</location>
    </error-page>
</web-app>

---404.html错误页面

<html>
    <head>
      <style type="text/css">
         h2{
           color: red;
         }
      </style>
    </head>
    <body>
        <h2>
            错误了!!!
        </h2>
    </body>
</html>

总结:与关系型数据库的连接一样,没有什么区别。

posted @ 2016-08-21 17:43  霓羽决奕  阅读(19386)  评论(1编辑  收藏  举报