MongoDB:mongodb在项目开发时的安全验证、分页查询操作
MongoDB:mongodb在项目开发时的安全验证、分页查询操作。 对于数据库而言,在项目应用中都需要安全验证,不然,就会报错,呵呵~~ 现在贴出来我在项目中是怎么做的。 数据源bean: package com.ishowchina.user.dao;import com.mongodb.BasicDBObject;impo
MongoDB:mongodb在项目开发时的安全验证、分页查询操作。
对于数据库而言,在项目应用中都需要安全验证,不然,就会报错,呵呵~~
现在贴出来我在项目中是怎么做的。
数据源bean:
package com.ishowchina.user.dao; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; public class DataSource { private String ip;//数据库连接信息要从配置文件中获取 参考appconfig.properties文件 private Integer port; protected String dbName; protected Boolean auth; protected String userName; protected String passWord; //打开连接 此处在获取数据库信息(ip、账户、密码等)后,打开数据库。 public MongoClient OpenConnection() throws Exception{ MongoClient mongoClient = new MongoClient( ip,port); return mongoClient; } //获取数据集 此处为数据库安全验证 public DBCollection getCollection(MongoClient client,String tableName){ if(client==null){ return null; }else { DB db = client.getDB(getDbName());//获取数据库 boolean r=true;//验证用户及密码 if(auth!=null && auth.equals(true)){ r = db.authenticate(userName, passWord.toCharArray());//密码验证 } if(r){ DBCollection coll = db.getCollection(tableName);//获取数据集 return coll; }else { return null; } } } //释放连接 public void ReleaseConnection(MongoClient mongoClient){ if(mongoClient!=null){ mongoClient.close(); } } //删除操作,注意要传入参数 public void deleteObject(DBObject o,DBCollection col){ col.remove(o); } //分页查询 分页查询mongodb已经为我们集成了,只需调用api就行 public DBCursor queryPage(DBObject query,DBObject sort,int start,int limit,DBCollection col){ //.sort('account',1).limit(10),int count = cursor.count() BasicDBObject exp=new BasicDBObject("_id",0); return col.find(query,exp).sort(sort).skip(start).limit(limit); } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getDbName() { return dbName; } public Boolean getAuth() { return auth; } public void setAuth(Boolean auth) { this.auth = auth; } public void setDbName(String dbName) { this.dbName = dbName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } }
appconfig.properties配置文件的内容,配置数据库源信息
mongo.ip=160.0.0.243 mongo.port=27017 mongo.auth=true mongo.user=ucenter mongo.pwd=user2show mongo.dbName=ucenter
spring-servlet.xml
<!-- 导入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:appconfig.properties</value> </list> </property> </bean>
这样做还不够,虽然知道了去那找数据库配置信息,但是,怎么获取数据库配置信息呢,还是在spring-servlet.xml里。
<!-- 数据源 --> <bean id="dataSource" class="com.ishowchina.user.dao.DataSource"><!-- 此处是和我们的数据库bean是对应关系 --> <property name="ip" value="${mongo.ip}"/> <!-- 此处是去appconfig.properties里找关键字对应的数据库信息 --> <property name="port" value="${mongo.port}"/> <property name="dbName" value="${mongo.dbName}"/> <property name="auth" value="${mongo.auth}"/> <property name="userName" value="${mongo.user}"/> <property name="passWord" value="${mongo.pwd}"/> </bean>
举个例子:
public DBObject getUserInfo(DBObject o) throws Exception{ MongoClient mongoClient = dataSource.OpenConnection(); DBCollection coll = dataSource.getCollection(mongoClient,tableName);//获取数据集userinfo //mongoClient.setWriteConcern(WriteConcern.JOURNALED);//Setting Write Concern BasicDBObject exp=new BasicDBObject("_id",0);//排除ID字段 DBObject myDoc = coll.findOne(o,exp); dataSource.ReleaseConnection(mongoClient) ;//释放连接 return myDoc; }

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Binance C2C Trading Guide: Safe and convenient way to deposit and withdraw money in cryptocurrency. This article will explain the Binance C2C (CustomertoCustomer) trading model in detail, explain its security, characteristics and operation procedures, and provide graphic tutorials to help you easily master the Binance C2C deposit and withdraw money in ease. What is Binance C2C? Binance C2C is a user-to-user cryptocurrency trading service provided by the Binance platform, providing users with convenient cryptocurrency and fiat currency exchange channels. Launched in 2019, the service supports multiple cryptocurrencies and fiat currency transactions through a peer-to-peer trading model, and provides enhanced security and multiple features. Compared with traditional OTC trading, Binance C2C platform authenticates both parties to the transaction and provides complete support.

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

As a new financial field, the currency circle has many participants and large market fluctuations. Withdrawing money has always been an important topic that investors pay attention to. Even if you have been in the currency circle for many years, you will encounter some troubles, and even have your account frozen. To this end, understand how to withdraw funds in the currency circle in the safest and most reliable way? It is knowledge that investors must master. Judging from the current data analysis, if you want to withdraw money safely and reliably, investors need to choose a reliable trading platform, protect personal information, click on any links carefully, etc. Next, the editor will explain it in detail. What is the safest and most reliable way to withdraw money from the currency circle? Withdrawals from Coin Circle can improve the efficiency of withdrawals by choosing regular platforms, multiple withdrawal channels, setting safe passwords, treating information with caution, protecting personal information, and regularly reviewing account funds.

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea
