SSM个人博客项目实战01

来源:互联网 发布:纸模软件 编辑:程序博客网 时间:2024/06/05 09:24

1. 使用的环境

  这个博客系统准备使用SpringMVC+MyBatis+Spring来搭建,后台管理使用EasyUI,前台使用Bootstrap。使用Apache的Shiro架构来实现安全认证,使用Apache的Lucene全文检索引擎架构实现全站的检索。数据库用的是mysql,数据库连接池用的是阿里巴巴的Druid,整个项目工程使用Maven来管理。基本环境就是这样子,后面有什么改动再做补充,下面开始搭建,先看一下pom.xml,我已经用注释将它们归归类了。

<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>ssm.blog</groupId>  <artifactId>Blog</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <dependencies>    <!-- 添加sevlet支持 -->    <dependency>        <groupId>Javax.servlet</groupId>        <artifactId>javax.servlet-api</artifactId>        <version>3.1.0</version>    </dependency>    <!-- 添加jsp支持 -->    <dependency>        <groupId>javax.servlet.jsp</groupId>        <artifactId>javax.servlet.jsp-api</artifactId>        <version>2.3.1</version>    </dependency>    <!-- 添加jstl支持 -->    <dependency>        <groupId>javax.servlet</groupId>        <artifactId>jstl</artifactId>        <version>1.2</version>    </dependency>    <!-- 添加spring支持 -->    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-core</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-beans</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-context</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-context-support</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-web</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-webmvc</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-tx</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-jdbc</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <dependency>    <groupId>org.springframework</groupId>        <artifactId>spring-aop</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-aspects</artifactId>        <version>4.3.0.RELEASE</version>    </dependency>    <!-- 添加mybatis支持 -->    <dependency>        <groupId>org.mybatis</groupId>        <artifactId>mybatis</artifactId>        <version>3.4.0</version>    </dependency>    <dependency>        <groupId>org.mybatis</groupId>        <artifactId>mybatis-spring</artifactId>        <version>1.3.0</version>    </dependency>    <!--  jdbc驱动包 -->    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>5.1.38</version>    </dependency>    <!-- 添加阿里巴巴连接池Druid支持 -->    <dependency>        <groupId>com.alibaba</groupId>        <artifactId>druid</artifactId>        <version>1.0.16</version>    </dependency>    <!-- 添加日志支持 -->    <dependency>        <groupId>log4j</groupId>        <artifactId>log4j</artifactId>        <version>1.2.17</version>    </dependency>    <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-api</artifactId>        <version>1.7.21</version>    </dependency>    <!-- 添加Shiro支持 -->    <dependency>        <groupId>org.apache.shiro</groupId>        <artifactId>shiro-core</artifactId>        <version>1.2.5</version>    </dependency>    <dependency>        <groupId>org.apache.shiro</groupId>        <artifactId>shiro-web</artifactId>        <version>1.2.5</version>    </dependency>    <dependency>        <groupId>org.apache.shiro</groupId>        <artifactId>shiro-spring</artifactId>        <version>1.2.5</version>    </dependency>    <!-- 添加lucene支持 -->    <dependency>        <groupId>org.apache.lucene</groupId>        <artifactId>lucene-core</artifactId>        <version>6.1.0</version>    </dependency>    <dependency>        <groupId>org.apache.lucene</groupId>        <artifactId>lucene-queryparser</artifactId>        <version>6.1.0</version>    </dependency>    <dependency>        <groupId>org.apache.lucene</groupId>        <artifactId>lucene-analyzers-common</artifactId>        <version>6.1.0</version>    </dependency>    <!-- Apache共公包 -->    <dependency>        <groupId>commons-codec</groupId>        <artifactId>commons-codec</artifactId>        <version>1.10</version>    </dependency>       <dependency>        <groupId>commons-lang</groupId>        <artifactId>commons-lang</artifactId>        <version>2.6</version>    </dependency>       <dependency>        <groupId>commons-beanutils</groupId>        <artifactId>commons-beanutils</artifactId>        <version>1.8.3</version>    </dependency>       <dependency>        <groupId>commons-collections</groupId>        <artifactId>commons-collections</artifactId>        <version>3.2.2</version>    </dependency>       <dependency>        <groupId>commons-logging</groupId>        <artifactId>commons-logging</artifactId>        <version>1.2</version>    </dependency>       <dependency>        <groupId>net.sf.ezmorph</groupId>        <artifactId>ezmorph</artifactId>        <version>1.0.6</version>    </dependency>    <!-- 添加百度编辑器ueditor支持 -->    <!-- 还有几个maven仓库中没有,我放到lib下了 -->    <dependency>        <groupId>commons-fileupload</groupId>        <artifactId>commons-fileupload</artifactId>        <version>1.3.2</version>    </dependency>    <!-- 添加junit支持 -->    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.12</version>      <scope>test</scope>    </dependency>  </dependencies>  <build>    <finalName>Blog</finalName>  </build>
</project>
之前在我的一篇多线程的博文中,有个网友给我回复说现在阿里巴巴的Druid连接池用的也比较多,所以这次我准备使用这个Druid连接池,阿里巴巴的产品应该不会让我们失望的,不过我没有深入的去研究这个,到时候再说吧,了解一下也不错~

2. 表的设计

  由于现在只是搭建一个架构,所以表的话目前我先建几个,但是只设置了id字段,其他字段还没设置,在我具体写项目的时候再来添加,因为具体的需求我还没想全,到时候再添加也不迟,主要建了下面几张表:

表名作用t_blogger博主信息表t_blog博客信息表t_blogType博客类型表t_comment评论信息表t_link友情链接表

目前就建了这几个,到时候再说吧。

3. 项目工程结构搭建

  接下来就是将项目整个架构给弄好,比如一些配置文件啊,一些包啊,包括简单的java程序啊等等。
先来把部分配置文件搞定,首先是日志的配置文件log4j.properties,这个我都是从官方给的贴过来的,如下:
log4j.rootLogger=DEBUG, Console  #Console  log4j.appender.Console=org.apache.log4j.ConsoleAppender  log4j.appender.Console.layout=org.apache.log4j.PatternLayout  log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  log4j.logger.java.sql.ResultSet=INFO  log4j.logger.org.apache=INFO  log4j.logger.java.sql.Connection=DEBUG  log4j.logger.java.sql.Statement=DEBUG  log4j.logger.java.sql.PreparedStatement=DEBUG

接下来就是在web.xml中添加Spring监听器、Shiro过滤器和SpringMVC的支持,以及其他一些配置:

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>Blog</display-name>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  <!-- spring监听器 -->  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <!-- spring配置文件 -->  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext.xml</param-value>  </context-param>  <!-- 添加springmvc支持 -->  <servlet>    <servlet-name>springMVC</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>    <async-supported>true</async-supported>  </servlet>  <servlet-mapping>    <servlet-name>springMVC</servlet-name>    <url-pattern>*.do</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>springMVC</servlet-name>    <url-pattern>*.html</url-pattern> <!-- 伪静态 -->  </servlet-mapping>  <!-- 添加shiro过滤器 -->  <filter>    <filter-name>shiroFilter</filter-name>    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    <init-param>        <!-- 该值缺省为false,表示声明周期由SpringApplicationContext管理,设置为true表示ServletContainer管理 -->        <param-name>targetFilterLifecycle</param-name>        <param-value>true</param-value>    </init-param>  </filter>  <filter-mapping>    <filter-name>shiroFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>  <!-- 编码过滤器 -->  <filter>    <filter-name>encodingFilter</filter-name>    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>    <async-supported>true</async-supported>    <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></web-app>
然后去配Spring的配置文件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:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="            http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd          http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd          http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-4.0.xsd          http://www.springframework.org/schema/jee         http://www.springframework.org/schema/jee/spring-jee-4.0.xsd          http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    <!-- 自动扫描包中的bean -->    <context:component-scan base-package="ssm.blog.service" />    <!-- 配置数据源,使用阿里巴巴连接池Druid -->    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">        <property name="url"            value="jdbc:mysql://localhost:3306/db_blog?useUnicode=true&amp;characterEncoding=UTF-8" />        <property name="username" value="root" />        <property name="password" value="root" />    </bean>    <!-- 配置mybatis的sqlSessionFactory -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <!-- 自动扫描mappers.xml文件 -->        <property name="mapperLocations" value="classpath:ssm/blog/mappers/*.xml"></property>        <!-- 加载mybatis全局配置文件 -->        <property name="configLocation" value="classpath:mybatis-config.xml"></property>    </bean>    <!-- 扫描mapper接口(即dao),Spring会自动查找其下的类 -->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="basePackage" value="ssm.blog.dao" />        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>    </bean>    <!-- 事务管理(transaction manager) -->    <bean id="transactionManager"        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource" />    </bean>    <!-- 自定义Realm -->    <bean id="myRealm" class="ssm.blog.realm.MyRealm" />    <!-- 安全管理器 -->    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">        <property name="realm" ref="myRealm" />    </bean>    <!-- Shiro过滤器 -->    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">        <!-- Shiro的核心安全接口,这个属性是必须的 -->        <property name="securityManager" ref="securityManager" />        <!-- 身份认证失败,则跳转到登录页面的配置 -->        <property name="loginUrl" value="/login.jsp" />        <!-- 权限认证失败,则跳转到指定页面,因为个人博客就一个人登陆,就不需要权限了 -->        <!-- <property name="unauthorizedUrl" value="http://blog.csdn.net/unauthorized.jsp" />  -->        <!-- Shiro连接约束配置,即过滤链的定义 -->        <property name="filterChainDefinitions">            <value>                /login=anon                /admin/**=authc            </value>        </property>    </bean>    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />    <!-- 开启Shiro注解 -->    <bean        class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"        depends-on="lifecycleBeanPostProcessor" />    <bean        class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">        <property name="securityManager" ref="securityManager" />    </bean>    <!-- 配置事务通知属性 -->    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <!-- 定义事务传播属性 -->        <tx:attributes>            <tx:method name="insert*" propagation="REQUIRED" />            <tx:method name="update*" propagation="REQUIRED" />            <tx:method name="edit*" propagation="REQUIRED" />            <tx:method name="save*" propagation="REQUIRED" />            <tx:method name="add*" propagation="REQUIRED" />            <tx:method name="new*" propagation="REQUIRED" />            <tx:method name="set*" propagation="REQUIRED" />            <tx:method name="remove*" propagation="REQUIRED" />            <tx:method name="delete*" propagation="REQUIRED" />            <tx:method name="change*" propagation="REQUIRED" />            <tx:method name="check*" propagation="REQUIRED" />            <tx:method name="get*" propagation="REQUIRED" read-only="true" />            <tx:method name="find*" propagation="REQUIRED" read-only="true" />            <tx:method name="load*" propagation="REQUIRED" read-only="true" />            <tx:method name="*" propagation="REQUIRED" read-only="true" />        </tx:attributes>    </tx:advice>    <!-- 配置事务切面 -->    <aop:config>        <aop:pointcut id="pointCut" expression="execution(* ssm.blog.service.*.*(..))" />        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut" />    </aop:config></beans>
这里数据源,使用的是阿里巴巴连接池Druid,由于包已经导入了,在包里面有个com.alibaba.druid.pool.DruidDataSource类就是Druid数据源,配一下即可。关于Shiro的配置,我在前面Shiro的博文中已经解释过了,在这里就不多做解释了,可以从我的文章目录中找到Shiro部分看一下即可。spring配置文件搞定了,里面也配置了数据源,sessionFactory,那么接下来就开始搞mybatis。
  首先配置一下mybatis的全局配置文件mybatis-config.xml,因为数据源啥的都交给spring管理了,所以全局配置文件就比较清爽了,当然还有一些设置上的东西,比如缓存啊等等,这里就不配置了,这个要看具体实际中使用的时候再配置。
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 别名 -->    <typeAliases>        <package name="ssm.blog.entity"/>    </typeAliases></configuration>
这里只配了个扫描ssm.blog.entity包中的实体,那就顺水推舟,把这个包中的entity写了呗,现在只写一个博主信息,后面有别的再添加。
/** * @Description 博主实体 * @author Ni Shengwu * */public class Blogger {    private Integer id;    private String username;    private String password;    //省去get set方法}

接下来再配置mapper配置文件:BloggerMapper.xml,如下:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="ssm.blog.dao.BloggerDao">    <resultMap type="Blogger" id="BloggerResult">        <result property="id" column="id"/>        <result property="username" column="username"/>        <result property="password" column="password"/>    </resultMap></mapper>
我就写了个resultMap,其实目前先不写也行,后面用到什么就往里面加什么。然后指定namespace为ssm.blog.dao包下的BloggerDao接口,那么下面把这个接口给写了。

/** * @Description 博主dao接口 * @author Ni Shengwu * */public interface BloggerDao {}
哈哈,里面啥也没有,因为现在还没有需求,而且这个接口中的方法也是根据上面的mapper配置文件来的。目前只是把项目架构给写好,如果从上面读下来,你会发现我的思路很清晰,一路顺水搞下来。这个dao就相当于mapper接口,不用实现,等用的时候spring会实例化一个代理对象去执行里面的方法。现在dao有了,接下来就把service层给写了呗!

/** * @Description 博主Service接口 * @author Ni Shengwu * */public interface BloggerService {}
也是个空壳,当然了,顺带把service实现类给写了。

/** * @Description 博主Service实现类 * @author Ni Shengwu * */@Service("bloggerService")public class BloggerServiceImpl implements BloggerService {}
注解啥的现在就可以加上去了,否则后面忘了,又会报错找不着这个bean啥的,所以顺带把注解加上。看着这些类都是空壳感觉很爽,因为后会一点点往里面塞东西,很喜欢这种感觉,让自己的项目越来越充实。
  写好了service层,接下来就是controller层了,controller层分为前台的controller和后台的controller,前台的controller不需要身份认证,因为不管是谁都能访问我的博客,但是后台的controller就需要认证了,只有我自己,或者说只有管理员才能登录进来访问。所以从上面工程的结构图中会看到有两个controller包。下面挨个来把两个controller的架子给搭好。

/** * @Description 博主Controller层,前台部分,不需要认证 * @author Ni Shengwu * */@Controller@RequestMapping("/blogger")public class BloggerController {    @Resource    private BloggerService bloggerService;}

/** * @Description 管理员博主Controller层,需要身份认证 * @author Ni Shengwu * */@Controller@RequestMapping("/admin/blogger")public class BloggerAdminController {}
可以看到,前台controller和后台controller匹配的url是不一样的,现在结合上面spring的配置文件中shiro部分的配置可知,当请求/admin*的时候要进行身份认证,所以我把url设置成了/admin/blogger,现在就能把这两者给串起来了。
  说到了认证,很自然想到spring配置文件中还有个自定义的realm,因为认证的时候会去请求我们自己定义的realm,所以现在可以去写自定义realm了。自定义realm需要继承AuthorizingRealm 类,并实现两个方法,如下:

/** * @Description 自定义realm * @author Ni Shengwu * */public class MyRealm extends AuthorizingRealm {    /**     * 为当前登陆的用户授予角色和权限     */    @Override    protected AuthorizationInfo doGetAuthorizationInfo(            PrincipalCollection principals) {        // 这个个人博客项目是不需要进行角色和权限认证的,因为就一个用户        return null;    }    /**     * 对前登陆的用户进行身份认证     */    @Override    protected AuthenticationInfo doGetAuthenticationInfo(            AuthenticationToken token) throws AuthenticationException {        // TODO Auto-generated method stub        return null;    }}

关于自定义realm部分的,如果不太明白,可以看一下我写的shiro自定义realm的那篇文章,shiro总共也就写了那几篇,也不多。
  好了,现在好像各个层的框架都搭好了,最后就是把springmvc的配置给搞好就行了,即配置spring-mvc.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:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="            http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd          http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd          http://www.springframework.org/schema/mvc           http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd        http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-4.0.xsd          http://www.springframework.org/schema/jee         http://www.springframework.org/schema/jee/spring-jee-4.0.xsd          http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    <!-- 扫描所有ssm.blog.controller包下面的所有controller -->    <context:component-scan base-package="ssm.blog.controller" />    <!-- 配置注解映射器和注解适配器 -->    <mvc:annotation-driven></mvc:annotation-driven>    <!-- 静态资源解析,包括js,css,img... -->    <mvc:resources location="/static/" mapping="/static/**"></mvc:resources>    <!-- 视图解析器 -->    <bean id="viewResolver"        class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/" />        <property name="suffix" value=".jsp" />    </bean>    <!-- 文件上传 -->    <bean id="multipartResolver"        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <property name="maxUploadSize" value="10000000" />        <property name="defaultEncoding" value="utf-8" />    </bean></beans> 
到这里,整个工程的架构就基本上搭建好了,还有一个问题,就是pom.xml文件中关于百度的ueditor编辑器在maven仓库中没有找到,所以还有几个jar包只能放到WEB-INF/lib中了,如下:

这样整个架构就搭建好了,部署一下工程,开启tomcat,运行一下http://localhost:8080/Blog瞧一瞧能否输出index.jsp中的内容。
  

【注】本项目我已敲完,源码已经上传github,博客上会更新完整进度,欢迎大家关注我的博客~
github地址:https://github.com/eson15/Blog。欢迎大家star我的工程,follow一下也是极好的~


阅读全文
0 0