当前位置: 代码迷 >> MySQL >>   路由
  详细解决方案

  路由

热度:106   发布时间:2016-05-05 16:46:59.0
基于tomcat+spring+mysql搭建的个人博客

  基于tomcat和spring开发的个人博客, 服务器是基于tomcat, 用了spring框架, web.xml的配置简单明了,我们只要配置MYSQL和用户过滤器等, 服务器的jsp就是负责VIEW, 用户通过ajax请求, 与服务器进行交互, 编辑器使用了百度的UEeditor;;

     

  数据表

  数据库有四个表,一切基于数据进行展开, 用户表, 博客内容表, 博客评论表以及友情链接的表:

//用户表;CREATE TABLE `user` (  `username` varchar(20) NOT NULL DEFAULT '',  `password` varchar(20) DEFAULT NULL,  PRIMARY KEY (`username`)) ENGINE=InnoDB DEFAULT CHARSET=gb2312 COMMENT='用户';//博客内容表;CREATE TABLE `article` (  `Id` int(11) NOT NULL AUTO_INCREMENT,  `title` varchar(50) DEFAULT NULL,  `content` text,  `username` varchar(50) DEFAULT NULL,  `date` datetime DEFAULT NULL,  PRIMARY KEY (`Id`),  KEY `username` (`username`),  CONSTRAINT `article_ibfk_1` FOREIGN KEY (`username`) REFERENCES `user` (`username`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=gb2312 COMMENT='博客内容';//博客评论;CREATE TABLE `critique` (  `Id` int(11) NOT NULL AUTO_INCREMENT,  `AId` int(11) DEFAULT NULL,  `content` text,  `username` varchar(50) DEFAULT NULL,  PRIMARY KEY (`Id`),  KEY `AId` (`AId`),  CONSTRAINT `critique_ibfk_1` FOREIGN KEY (`AId`) REFERENCES `article` (`Id`)) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=gb2312 COMMENT='博客评论';//友情链接的表CREATE TABLE `links` (  `name` varchar(20) NOT NULL DEFAULT '',  `url` varchar(80) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=gb2312 COMMENT='友情链接';
View Code

 

  路由

  首页的路由和用户的路由: 所有博客内容列表路由, 博客登录路由, 博客的详细内容路由, 写博客的路由, 比如登录路由和写博客的路由既包含post也包含get

  主界面路由 MainCon.java

package com.nono.Controller;import java.util.ArrayList;import javax.naming.LinkRef;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import net.sf.jsqlparser.expression.operators.arithmetic.Addition;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.RequestMethod;import org.springframework.web.servlet.ModelAndView;import com.nono.Dao.GetLinks;import com.nono.Service.CompareUserService;import com.nono.Service.GetAllArticle;import com.nono.po.ArticlePo;import com.nono.po.Link;@Controllerpublic class MainCon {        @Autowired    CompareUserService compareUserService;        @Autowired    GetAllArticle getAllArticle;    @Autowired    GetLinks getLinks;        @RequestMapping(value="index",method = RequestMethod.GET)    public ModelAndView index(ServletRequest request, ServletResponse response) {        ArrayList<ArticlePo> list = getAllArticle.getAll();        ModelAndView maView = new ModelAndView("list-index");        maView.addObject("list", list);        maView.addObject("links", getLinks.getLinks());        ArrayList<Link> links = getLinks.getLinks();        return maView;    }    @RequestMapping(value="login",method = RequestMethod.GET)    public String login(ServletRequest request, ServletResponse response) {        return "login";    }    @RequestMapping(value="login",method = RequestMethod.POST)    public ModelAndView loginPost(HttpServletRequest request, HttpServletResponse response) {        String nameString = (String)request.getParameter("username");        String password = (String)request.getParameter("password");        //获取session;        HttpSession session = request.getSession(false);        ModelAndView mav;        Boolean boolean1 = compareUserService.isRightPassword(nameString, password);        ArrayList<ArticlePo> list = getAllArticle.getAll();                if(boolean1 == true) {            mav = new ModelAndView("list-index");            //设置用户名字为session;            session.setAttribute("user", nameString);                        mav.addObject("list", list);            mav.addObject("links", getLinks.getLinks());        }else{            mav = new ModelAndView("login");             mav.addObject("state", "密码错误");        };        mav.addObject("links", getLinks.getLinks());        return mav;     }    }
View Code

  博客的详细内容和写博客的路由 ArticleCon.java

package com.nono.Controller;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;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.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import com.nono.Dao.AddArt;import com.nono.Dao.AddCommentDao;import com.nono.Dao.GetLinks;import com.nono.Service.GetArticalByIdService;import com.nono.po.ArticlePo;@Controller@RequestMapping ("user")  public class ArticleCon {        @Autowired    GetArticalByIdService getArticalByIdSer;        @Autowired    AddCommentDao addCommentDao;        @Autowired    GetLinks getLinks;        @Autowired    AddArt addArt;        @RequestMapping(value="add", method=RequestMethod.GET)     public String addArticle(ServletRequest request, ServletResponse response) {        return "addArticle";    }    @RequestMapping(value="show", method=RequestMethod.GET)     public ModelAndView showArticle(ServletRequest request, ServletResponse response) {        ModelAndView mavAndView = new ModelAndView("showArticle");        int articalID = Integer.parseInt( request.getParameter("aid") );        ArticlePo articlePo = getArticalByIdSer.getByAid( articalID );        mavAndView.addObject("art", articlePo);        mavAndView.addObject("coms", getArticalByIdSer.getComByAid(articalID));        mavAndView.addObject("links", getLinks.getLinks());        return mavAndView;    }    @RequestMapping(value="addComment",method=RequestMethod.POST)    @ResponseBody    public String post(ServletRequest request, ServletResponse response) {        String string = "false";        String aid = request.getParameter("aid");        String name = request.getParameter("name");        String content = request.getParameter("content");        if(true == addCommentDao.addCommentDao(aid, name, content) ) {            string = "true";        };        return string;    }        @RequestMapping(value="addArt",method=RequestMethod.POST)    @ResponseBody    public String addArt(ServletRequest request, ServletResponse response) {        String string = "false";        String content = request.getParameter("content");        String title = request.getParameter("title");        if(true == addArt.addArt(title, content) ) {            string = "true";        };        return string;    }    }
View Code

 

 

  项目的结构如图:

  

  

  web.xml和application-servlet.xml的配置:

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0"     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_3_0.xsd">  <display-name></display-name>      <welcome-file-list>    <welcome-file>index.htm</welcome-file>  </welcome-file-list>    <servlet>    <servlet-name>application</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>    <servlet-name>application</servlet-name>    <url-pattern>*.do</url-pattern>    </servlet-mapping>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>            <!--         使用Spring中的过滤器解决在请求和应答中的中文乱码问题         -->     <filter>        <filter-name>characterEncodingFilter</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>        <init-param>                <!--                 强制转换编码(request和response均适用)                 -->             <param-name>ForceEncoding</param-name>            <param-value>true</param-value>        </init-param>    </filter>        <filter>          <filter-name>SecurityServlet</filter-name>          <filter-class>com.nono.Filter.UserFilter</filter-class>      </filter>      <filter-mapping>          <filter-name>SecurityServlet</filter-name>          <url-pattern>*.do</url-pattern>      </filter-mapping>                <context-param>        <param-name>        contextConfigLocation        </param-name>        <param-value>        /WEB-INF/application-servlet.xml        </param-value>    </context-param></web-app>
View Code
<?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: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" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" 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/tx      http://www.springframework.org/schema/tx/spring-tx-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/mvc      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd      http://www.springframework.org/schema/task      http://www.springframework.org/schema/task/spring-task-3.0.xsd">        <context:annotation-config> </context:annotation-config>    <context:component-scan base-package="com.nono" > </context:component-scan>        <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">       <property name="driverClassName"  value="com.mysql.jdbc.Driver" />     <property name="url" value="jdbc:mysql://127.0.0.1:3306/db_blog_" />     <property name="username" value="root" />     <property name="password" value="111111" />    </bean>           <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" abstract="false" lazy-init="false" autowire="default">        <!-- 把这个bean传进去 -->        <property name="dataSource" ref="dataSource">        </property>    </bean>        <bean id="jdbcDao" class="com.nono.Dao.JdbcDao">        <property name="jdbcTemplate" ref="jdbcTemplate"></property>    </bean>          <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="suffix">            <value>.jsp</value>        </property>    </bean></beans>
View Code

 

 

  

  使用了Filter过滤器实现用户只有登录的情况下才能发布博客, 否则只能允许跳转到登录界面, 主界面如下:       

  

  下面为静态界面, 包含登录页, 首页, 博客详细页, 添加博客页,( •? ω •? )y;

  login.do:

<%@ page language="java" contentType="text/html; charset=utf-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><title>博客系统登录</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link type="text/css" rel="stylesheet" href="css/main.css" media="all" /><!--[if IE 6]><link type="text/css" rel="stylesheet" href="css/ie6.css" media="all" /><![endif]--><script type="text/javascript" src="js/mootools.js"></script><script type="text/javascript" src="js/site.js"></script></head><body><div id="wrapper">  <div id="container">    <div id="scene"> <img src="images/scene.jpg" alt="" />      <div id="scale_area">        <div id="scale_knob">&raquo; Font Size &laquo;</div>      </div>    </div>    <div id="content">      <div id="col_left">        <div class="post">          <div class="meta"></div>          <div class="comments"><div class="comment"></div>            <h2>博客登录</h2>            <form class="h" method="post">                <p>                ${state}                </p>              <div>                <label>用户名:</label>                <input type="text" name="username" />              </div>              <div>                <label>密码:</label>                <input type="password" name="password" />              </div>              <div>                <label></label>                <div class="clear"> </div>              </div>              <div class="button_wrapper">                <input name="提交" type="submit" class="button" value="登录" />              </div>            </form>          </div>        </div>      </div>      <div id="col_right">        <div id="links">            <c:forEach items="${links}" var="item">                <a href="${item.url}"> ${item.name} </a>            </c:forEach>        </div>        <div id="sidebar">          <h2>页面导航</h2>          <ul>              <li class="holder"> <a href="index.do">文章列表</a> </li>              <c:if test="${user==null}">                <li class="holder"> <a href="login.do">博客登录</a> </li>              </c:if>              <c:if test="${user!=null}">                <li class="holder"> <a href="user/add.do">写新博客</a> </li>              </c:if>          </ul>        </div>      </div>      <div class="clear"> </div>    </div>    <div id="footer">      <div class="clear"> </div>      <hr />      <p class="credit">博客网站系统</p>    </div>  </div></div></body></html>
View Code

  index.do:

<%@ page language="java" contentType="text/html; charset=utf-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><title>博客系统首页</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link type="text/css" rel="stylesheet" href="css/main.css" media="all" /><!--[if IE 6]><link type="text/css" rel="stylesheet" href="css/ie6.css" media="all" /><![endif]--><script type="text/javascript" src="js/mootools.js"></script><script type="text/javascript" src="js/site.js"></script></head><body><div id="wrapper">  <div id="container">    <div id="scene">      <img src="images/scene.jpg" alt="" />      <div id="scale_area">        <div id="scale_knob">&raquo; Font Size &laquo;</div>      </div>    </div>    <div id="content">      <div id="col_left">        <div class="post">          <div class="meta"><a class="title" href="">博客系统首页</a>            <div class="clear"></div>          </div>        <!-- 循环输出 -->                <c:forEach items="${list}" var="item">                   <div class="comments">            <div class="comment">              <div class="meta"> <span><a href="user/show.do?aid=${item.id}">${item.title}</a> <small>:</small></span>                <div class="clear"> </div>              </div>              <div>                  ${item.content}              </div>            </div>            <div class="comment alt">              <div class="meta"><span class="datetime">                  <!-- 发表时间 -->                    发表于:                    ${item.date}              </span>                <div class="clear"> </div>              </div>            </div>          </div>                  </c:forEach>                </div>      </div>      <div id="col_right">        <div id="links">            <c:forEach items="${links}" var="item">                <a href="${item.url}"> ${item.name} </a>            </c:forEach>        </div>        <div id="sidebar">          <h2>页面导航</h2>          <ul>              <li class="holder"> <a href="index.do">文章列表</a> </li>              <c:if test="${user==null}">                <li class="holder"> <a href="login.do">博客登录</a> </li>              </c:if>              <c:if test="${user!=null}">                <li class="holder"> <a href="user/add.do">写新博客</a> </li>              </c:if>          </ul>        </div>      </div>      <div class="clear"> </div>    </div>    <div id="footer">      <div class="clear"> </div>      <hr />      <p class="credit">博客网站系统</p>    </div>  </div></div></body></html>
View Code

  add.do:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><title>添加文章</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link type="text/css" rel="stylesheet" href="../css/main.css" media="all" /><script src="http://cdn.bootcss.com/jquery/1.9.0/jquery.js"></script><!--[if IE 6]><link type="text/css" rel="stylesheet" href="css/ie6.css" media="all" /><![endif]--><script type="text/javascript" src="../js/mootools.js"></script><script type="text/javascript" src="../js/site.js"></script><script type="text/javascript" charset="utf-8" src="<%=basePath%>/editor/ueditor.config.js"></script><script type="text/javascript" charset="utf-8" src="<%=basePath%>/editor/ueditor.all.min.js"> </script><!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败--><!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文--><script type="text/javascript" charset="utf-8" src="<%=basePath%>/editor/lang/zh-cn/zh-cn.js"></script></head><body><div id="wrapper">  <div id="container">    <div id="scene"> <img src="../images/scene.jpg" alt="" />      <div id="scale_area">        <div id="scale_knob">&raquo; Font Size &laquo;</div>      </div>    </div>    <div id="content">      <div id="col_left">        <div class="post">          <div class="meta"></div>          <div class="comments"><div class="comment"></div>            <h2>添加文章</h2>              <div>                <label>标题:</label>                <input id="title" type="text" name="title" />              </div>              <div>                <label>内容:</label>                <div>                    <script id="c" type="text/plain"></script>                </div>              </div>              <div>                <label></label>                <div class="clear"> </div>              </div>              <div class="button_wrapper">                <input id="submit" name="提交" type="submit" class="button" value="提交" />              </div>            <script>                jQuery("#submit").click(function() {                    jQuery.post("addArt.do", {content:window.ue.getContent(), title: jQuery("#title").val()}, function( response ) {                        if(response === "true") {                            location.href = "../index.do";                        }                    });                });                jQuery(function(){                    window.ue = UE.getEditor('c');                });            </script>          </div>        </div>      </div>      <div id="col_right">        <div id="links">            <c:forEach items="${links}" var="item">                <a href="${item.url}"> ${item.name} </a>            </c:forEach>        </div>        <div id="sidebar">          <h2>页面导航</h2>          <ul>              <li class="holder"> <a href="../index.do">文章列表</a> </li>              <c:if test="${user==null}">                <li class="holder"> <a href="../login.do">博客登录</a> </li>              </c:if>              <c:if test="${user!=null}">                <li class="holder"> <a href="add.do">写新博客</a> </li>              </c:if>          </ul>        </div>      </div>      <div class="clear"> </div>    </div>    <div id="footer">      <div class="clear"> </div>      <hr />      <p class="credit">博客网站系统</p>    </div>  </div></div></body></html>
View Code

  show.do:

<%@ page language="java" contentType="text/html; charset=utf-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><title>我的文章</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link type="text/css" rel="stylesheet" href="../css/main.css" media="all" /><!--[if IE 6]><link type="text/css" rel="stylesheet" href="css/ie6.css" media="all" /><![endif]--><script src="http://cdn.bootcss.com/jquery/1.9.0/jquery.js"></script><script type="text/javascript" src="../js/mootools.js"></script><script type="text/javascript" src="../js/site.js"></script></head><body><div id="wrapper">  <div id="container">    <div id="scene">      <img src="../images/scene.jpg" alt="" />      <div id="scale_area">        <div id="scale_knob">&raquo; Font Size &laquo;</div>      </div>    </div>    <div id="content">      <div id="col_left">        <div class="post">          <div class="meta">          <a class="title" href="">${art.title}</a>            <div class="clear"></div>                  <div class="blog_content">                    ${art.content}                </div>          </div>          <c:forEach items="${coms}" var="item">          <div class="comments">            <div class="comment">              <div class="meta">              <span>                  ${item.username}:                  ${item.content}              </span>                <div class="clear"> </div>              </div>            </div>          </div>          </c:forEach>        <!-- 循环输出 -->                <div class="clear"> </div>          <div class="comment">              <h2>发表评论</h2>             <div>                <input id="c" type="text" value="" placeHolder="评论"/>                <input id="n" type="text" value="匿名" placeHolder="您的名字"/>                <br/>                <br/>              <div class="button_wrapper">                <input id="submit" name="提交" type="submit" class="button" value="提交" />              </div>            </div>            <script>            $("submit").addEvent("click",function(ev) {                jQuery.post("./addComment.do",{aid : location.href.substr(location.href.indexOf("aid")+4), name:jQuery("#n").val(), content:jQuery("#c").val()},function( res ){                    if(res==="true") {                        location.reload();                    };                });            });            </script>          </div>        </div>      </div>      <div id="col_right">        <div id="links">            <c:forEach items="${links}" var="item">                <a href="${item.url}"> ${item.name} </a>            </c:forEach>        </div>        <div id="sidebar">          <h2>页面导航</h2>          <ul>              <li class="holder"> <a href="../index.do">文章列表</a> </li>              <c:if test="${user==null}">                <li class="holder"> <a href="../login.do">博客登录</a> </li>              </c:if>              <c:if test="${user!=null}">                <li class="holder"> <a href="add.do">写新博客</a> </li>              </c:if>          </ul>        </div>      </div>      <div class="clear"> </div>    </div>    <div id="footer">      <div class="clear"> </div>      <hr />      <p class="credit">博客网站系统</p>    </div>  </div></body></html>
View Code

 

  项目源代码分享到百度云盘,jar包等都全部导出了,可作为参考:打开

 

作者: NONO
出处:http://www.cnblogs.com/diligenceday/
QQ:287101329 

3楼chuiyuan
多谢楼主,学习了
2楼crazyacking
ORZ,tomcat和spring组合确实很方便,楼主写得不错,赞一个!
1楼编程 浪子
不错哦,学习学习。
  相关解决方案