MongoDB+jsp 个人博客系统

简单实现,欢迎提出意见。

设计原因:

课设选题:设计一个个人博客系统,使用MongoDB。
其实使用MongoDB数据库来作为博客系统的话,个人觉着不是十分实用,但是全文检索功能需要使用到的MongoDB自身所带的检索系统,以及对于存储Tag标签的List,使用MongoDB的Json存储方式来进行十分便利,也方便于检索。
使用Foundation5作为前端样式,使用servlet处理数据库操作。

关于Foundation5,学习自菜鸟教程Foundation5

前期工作:

首先,导入Jsp连接MongoDB数据库必用的Jar包:
MongoDB+jsp 个人博客系统_第1张图片
本项目需要使用到的相关Jar包以及源码包,全部在网盘里,可以下载使用并Build path。
链接:相关ar包
提取码:onmr

图片展示:

对于MongoDB非关系型数据库的优点等不赘述,直接进行设计思路,先简单放几张程序最终截图:

MongoDB+jsp 个人博客系统_第2张图片
MongoDB+jsp 个人博客系统_第3张图片
MongoDB+jsp 个人博客系统_第4张图片MongoDB+jsp 个人博客系统_第5张图片
MongoDB+jsp 个人博客系统_第6张图片
MongoDB+jsp 个人博客系统_第7张图片

代码过程:

  1. 连接数据库部分:
package com.connect;

import java.io.Reader;
import java.sql.*;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.DB;
import com.mongodb.DBCollection; 
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public enum connect {
	instance;
	private MongoClient mongoClient;
	
	static {
		System.out.println("连接MongoDB成功");
		instance.mongoClient=new MongoClient("localhost",27017);
	}
	//获取数据库名称
	public MongoDatabase getDB(String dbName) {
		if(dbName!=null && !"".equals(dbName)) {
			MongoDatabase database = mongoClient.getDatabase(dbName);
			 return database;
		}
		return null;
	}
	
	//获取集合(表)
	public MongoCollection<Document> getCollection(String dbName,String collName){
		if(null == collName||"".equals(collName)) {
			return null;
		}if(null==dbName||"".equals(dbName)){
			return null;
		}
		MongoCollection<Document> collection=mongoClient.getDatabase(dbName).getCollection(collName);
		return collection;
	}
	//关闭mongoDB数据库
	public void close() {
		if(mongoClient!=null) {
			mongoClient.close();
			mongoClient=null;
		}
	}
	
	//条件查询
	public MongoCursor<Document> find(MongoCollection<Document> coll,Bson filter){
		if(null!=filter) {
			return coll.find(filter).iterator();
		}else {
			return coll.find().iterator();
		}
	}
	//插入数据
	public void insert(MongoCollection<Document> coll,Document doc) {
		coll.insertOne(doc);
	}
	//删除数据
	public void selete(MongoCollection<Document> coll,Document doc) {
		coll.deleteMany(doc);
	}
	//更新数据
	public void update(MongoCollection<Document> coll,Document querydoc,Document updatedoc) {
		coll.updateMany(querydoc,updatedoc);
	}
} 

使用到了Jar包自封的对MongoDB实现的CRUD函数,具体源码可查看源码包(已给出)。

  1. 对于数据接收的部分:
    文本列表设计:
    Text.java:
package com.model;

import java.util.List;
import org.bson.types.ObjectId;

public class Text {

	private String _id;
	private String title;//文章标题
	private String username;//文章作者,也是用户唯一标识(这里其实设计的不是十分好)
	private String content;//文章内容
	private String time;//文章发表时间
	private String remark;//文章标签分类
	private double like;//点赞量
	private double dislike;//点不赞量
	private List<String> tag;//用户全文检索的标签列表
	
	public String get_id() {
		return _id;
	}
	public void set_id(String _id) {
		this._id=_id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title=title;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username=username;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content=content;
	}
	public String getTime() {
		return time;
	}
	public void setTime(String time) {
		this.time=time;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark){
		this.remark=remark;
	}
	public double getLike() {
		return like;
	}
	public void setLike(double like) {
		this.like=like;
	}
	public double getDislike() {
		return dislike;
	}
	public void setDislike(double dislike) {
		this.dislike=dislike;
	}
	public List<String> getTag() {
		return tag;
	}
	public void setTag(List<String> tag) {
		this.tag = tag;
	}

	
//	
//	public String toString() {
//		return "[_id=" + _id + ", title=" + title+ ", username=" + username  + ", content=" + content +", time=" + time +  ", remark=" + remark + ",tag=" +tag+"]";
//	}
}

同理,用户列表:user.java :

package com.model;

import org.bson.types.ObjectId;

public class User {
	private String _id;
	private String username;
	private String password;
	private String remark;
	public String get_id() {
		return _id;
	}
	public void set_id(String _id) {
		this._id=_id;
	}
	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;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark=remark;
	}
	@Override
	public String toString() {
		return "User [_id=" + _id + ", username=" + username + ", password=" + password + ", remark=" + remark + "]";
	}
	
	

}

  1. 关于具体操作部分,这里放上一部分servlet对于数据库CRUD的操作过程:
    eg:
    FindText.java:实现了在未登录状态下进行文章浏览的操作,其中连接数据库,并获取对应的Json,最终使用request进行传递,传递给对应的FindAllText.jsp进行显示。
package com.textservlet;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;

import com.connect.connect;
import com.google.gson.Gson;
import com.model.Text;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;

@WebServlet("/FindText")
public class FindText extends HttpServlet{

	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public FindText() {
        // TODO Auto-generated constructor stub
    	super();
    }
    /**
	 * @throws IOException 
     * @throws ServletException 
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
    	String dbName="OpenPureLand";
    	String collName="TextList";
    	MongoCollection<Document> coll=connect.instance.getCollection(dbName,collName);
    	List<Text> TextList=new ArrayList<Text>();
        Bson filter = null;
        MongoCursor<Document> cursor = connect.instance.find(coll, filter);
        while(cursor.hasNext()){
        	Document tempdoc = cursor.next();
        	Text text =  new Text();
            text.set_id(tempdoc.get("_id").toString());
            text.setTitle(tempdoc.get("title").toString());
            text.setUsername(tempdoc.get("username").toString());
            text.setContent(tempdoc.get("content").toString());
            text.setTime(tempdoc.get("time").toString());
            text.setRemark(tempdoc.get("remark").toString());
            text.setLike(Double.parseDouble(tempdoc.get("like").toString()));
            text.setDislike(Double.parseDouble(tempdoc.get("dislike").toString()));
            TextList.add(text);
        }
		request.setAttribute( "TextList",TextList);
		request.getRequestDispatcher( "FindAllText.jsp").forward(request,response);	
    } 
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

FindText.jsp:这其中的CDN使用Fundtaion5的“申明”,接收俩字与servlet的request并进行

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@page import="java.util.*"%>
<%@page import="com.model.Text"%>
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <title>find</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.staticfile.org/foundation/5.5.3/css/foundation.min.css">
  <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://cdn.staticfile.org/foundation/5.5.3/js/foundation.min.js"></script>
  <script src="https://cdn.staticfile.org/foundation/5.5.3/js/vendor/modernizr.js"></script>
  <link rel="stylesheet" href="http://static.runoob.com/assets/foundation-icons/foundation-icons.css">
    <script>
		function displayResult()
		{
		var x;
		if(window.event) // IE8 以及更早版本
			{
			x=event.keyCode;
			}
		else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
			{
			x=event.which;
			}
		keychar=String.fromCharCode(x);
		
		if(event.keyCode == 13)  
			
		{  
			var stext = $("input[name='search_text']").val();
			
			window.location.href="searchText?search_text="+stext;
		}  
		
		}
</script>
  </head>
  <body>
  
<!-- 这里是导航栏 -->

<nav class="top-bar" data-topbar>
  <ul class="title-area">
    <li class="name">
      <h1><a href="#">净土</a></h1>
    </li>
    <li class="toggle-topbar menu-icon"><a href="#"><span>Menu</span></a></li>
  </ul>
  <section class="top-bar-section">
    <ul class="left">
      <li><a href="homepage.jsp">主页</a></li>
      <li class="divider"></li>
      <li class="active"><a href="#">文章</a></li>
      <li class="divider"></li>
      <li><a href="#">动态</a></li>
      <li class="divider"></li>
 <li>&nbsp;&nbsp;&nbsp;&nbsp;</li>
      <li><input type="text" class="input" name="search_text" placeholder="输入文章标题、作者或标签" onkeypress="displayResult()"/></li>
    </ul>
    <ul class="right">
    <li class="divider"></li>
      <li><a data-reveal-id="myModal">登陆</a></li>
      <li class="divider"></li>
      <li><a href="register.jsp">注册</a></li>
    </ul>
  </section>

</nav>
<!-- 这里是提示框 -->
  <div data-alert class="alert-box alert">
    <strong>注意!</strong>请您先进行登录!如果没有登陆将不能进行操作!
    <a href="#" class="close">&times;</a>
  </div>
<!-- 这里是登陆页面的div模式框的显示 -->
<div id="myModal" class="reveal-modal" data-reveal>
   <form action='FindUserByName' method="post">
  <fieldset>
    <legend>请您进行登陆</legend>
    <label>Username
      <input type="text" name="username" class="form-control" placeholder="username">
    </label>
    <label>Password
      <input type="password" name="password" class="form-control" placeholder="password">
    </label>
    <label>
      <button type="submit" class="btn btn-default">确定</button>
    </label>
  </fieldset>
</form>
    <a class="close-reveal-modal">&times;</a>
  </div>
<!-- 这里是文章展示列表 -->
<div style="padding:20px;"  align="center">
  <div class="panel callout" style="width:600px">
	
	<%
	    List<Text> list = new ArrayList<Text>();
		list =(List)request.getAttribute("TextList");
		for(int i=0;i<list.size();i++){
			Text text = list.get(i);
	
	%>
	<div style="padding:10px;">
  <div class="panel">
  <fieldset>
    <legend><%=text.getTime() %></legend>
    <B><%=text.getTitle() %></B>
    
    <label>
    <fieldset>
    <label><%=text.getContent() %></label>
    </fieldset>
    </label>
    <label style="text-align:right"><%=text.getUsername() %></label>
    
    <hr>
    <!--   <ul class="left"><h4 class=" fi-like"></h4></ul>
    <ul class="right"><h4 class=" fi-dislike"></h4></ul> -->
  
    
<!-- 这里是点赞与反对数的展示 -->
    <%
    double a=text.getLike();
    double b=text.getDislike();
    double d=a+b+1;
    double c=(a/(a+b))*100;
    double f = (a/(a+b))*100;
    //int e=Integer.parseInt(new java.text.DecimalFormat("0").format(c));
    int e = (int)f;
    %>
   
    <label> 
    <h7>点赞率:<%=e %>%</h7>
    <div class="range-slider round disabled" data-slider data-options="display_selector: #mySlider ; initial:<%=a%>;start: 1; end: <%=d%>;">
    <span class="range-slider-handle"></span>
    <span class="range-slider-active-segment"></span>
  </div> 
  </label>	
  <hr>
  </fieldset>
  </div>

</div>
	<%		
		}
	%>
  </div>
  </div>
  
  <!-- 初始化 Foundation JS -->
<script>
$(document).ready(function() {
    $(document).foundation();
})
</script>
  </body>
</html>

其余函数皆是同理,使用connect.java中函数接口,可以轻松实现对于MongoDB的CRUD。

全文检索

<script>
		function displayResult()
		{
		var x;
		if(window.event) // IE8 以及更早版本
			{
			x=event.keyCode;
			}
		else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
			{
			x=event.which;
			}
		keychar=String.fromCharCode(x);
		
		if(event.keyCode == 13)  
			
		{  
			var stext = $("input[name='search_text']").val();
			
			window.location.href="searchText?search_text="+stext;
		}  
		
		}
</script>

监听键盘事件,对于按下回车使用window.location.href给予跳转,更加美观。

此外,在MongoDB中TextList文章列表中,对于每一篇文章设置对应的TitleusernameRemark设置为Tag标签,直接进行find({"tag":"对应检索目标即可"})
具体的页面代码为:

package com.textservlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.connect.connect;
import com.model.Text;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
@WebServlet("/searchText")
public class searchText extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public searchText() {
		// TODO Auto-generated constructor stub
	}
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		String search_text=request.getParameter("search_text");
		String dbName="OpenPureLand";
    	String collName="TextList";
    	List<Text> TextList=new ArrayList<Text>();
    	MongoCollection<Document> coll=connect.instance.getCollection(dbName,collName);
    	Bson filter=Filters.eq("tag",search_text);
    	MongoCursor<Document> cursor = connect.instance.find(coll, filter);
    	while(cursor.hasNext()){
        	Document tempdoc = cursor.next();
        	Text text =  new Text();
            text.set_id(tempdoc.get("_id").toString());
            text.setTitle(tempdoc.get("title").toString());
            text.setUsername(tempdoc.get("username").toString());
            text.setContent(tempdoc.get("content").toString());
            text.setTime(tempdoc.get("time").toString());
            text.setRemark(tempdoc.get("remark").toString());
            text.setLike(Double.parseDouble(tempdoc.get("like").toString()));
            text.setDislike(Double.parseDouble(tempdoc.get("dislike").toString()));
            TextList.add(text);
        }
    	request.setAttribute( "TextList",TextList);
		request.getRequestDispatcher( "search.jsp").forward(request,response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

此页面实现对前端jsp发送的search_text内容的传送,并使用这一值进行检索全文,最后在返回相对应的Sraech.jsp页面进行显示即可。

其他:

  • 对于点赞与反对,使用Jquery选择ID值的方式进行获取,并在页面进行更改,本计划使用Ajax,但是页面逻辑写的比较乱(我太菜了),所以导致因为循环显示的页面,所以无法实现异步更新~
  • 其他代码之后会放到Gitub上,以供日后学习。
  • 之后总结报错以及原因。

总结:

用户可以在无论登录与否的情况下进行检索全文,或者是查看文章,但是不登录会有提示,登录用户可以进行发表文章,更新信息,退出登录,点赞或反对,程序并没有完全完整,比如说预设的动态列表,以及消息列表,关注列表等,因为时间关系没有实现。

简单实现,欢迎提出意见!

你可能感兴趣的:(javaweb,NoSQL)