SpringMVC注解功能丰富,使用简单,作为web框架。
Freemarker标签库非常强大,可以控制模版缓存时间性能也不错,view层使用。
Mybatis动态SQL,使用方便,作为持久层框架。
此外项目使用Mysql数据库,dbcp数据源,quartz管理定时任务。
一、jar包准备
使用maven构建项目管理jar包
<dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<!-- spring核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- springMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 整合freemarker -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 整合mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.3</version>
</dependency>
<!-- dbcp数据源 -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>8.0.24</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<!-- 手动切面配置 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.6</version>
</dependency>
<!-- 文件上传组件 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- mybatis分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.0</version>
</dependency>
<!-- mybatis整合log4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<!-- spring整合quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<!-- Springjdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
</dependencies>
二、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<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:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
三、配置springmvc-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="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/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 配置分离 -->
<import resource="classpath:applicationContext.xml" />
<!-- <import resource="classpath:taskJob.xml" /> -->
<!-- 自动扫描controller -->
<context:component-scan base-package="com.caicai.controller"></context:component-scan>
<!-- 注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 资源管理 -->
<mvc:resources location="/css/" mapping="/css/**" cache-period="31536000"/>
<mvc:resources location="/js/" mapping="/js/**" cache-period="31536000"/>
<mvc:resources location="/images/" mapping="/images/**" cache-period="31536000"/>
<mvc:resources location="/upload/" mapping="/upload/**"/>
<!-- 上传文件解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 1M -->
<property name="maxUploadSize" value="1048576"></property>
</bean>
<!-- Freemarker基本配置信息 -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/template/" />
<property name="defaultEncoding" value="utf-8" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
</props>
</property>
<!--设置一些常用的全局变量 -->
<property name="freemarkerVariables">
<map>
<entry key="contextPath" value="/day75_mybatis"></entry>
</map>
</property>
</bean>
<!-- FreeMarker视图解析器配置 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property>
<property name="suffix" value=".ftl" />
<property name="contentType" value="text/html;charset=utf-8" />
</bean>
<!-- jsp视图解析器基本配置 -->
<!--
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
-->
</beans>
四、配置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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="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/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 自动扫描service和dao -->
<context:component-scan base-package="com.caicai.dao"></context:component-scan>
<context:component-scan base-package="com.caicai.service"></context:component-scan>
<!-- 整合mybatis数据源 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!--数据库连接配置抽取出来单独创建jdbc.properties-->
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 整合关键配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--可选,如果还需要mybatis详细的配置可以配置在mybatis.xml中-->
<property name="configLocation" value="classpath:mybatis.xml"></property>
<property name="dataSource" ref="dataSource" />
<!--使用Mybatis自动实现,只需编写xml文档和接口即可,xml存放路径 -->
<property name="mapperLocations" value="classpath*:com/caicai/dao/*Mapper.xml"></property>
<!--Mybatis中的parameterType或resultType统一起把类名当作别名,放在配置的包中就用的时候直接写类名就行了-->
<property name="typeAliasesPackage" value="com.caicai.domain"></property>
<!-- 增加分页插件支持 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>
dialect=mysql
reasonable=true
</value>
</property>
</bean>
</array>
</property>
</bean>
<!-- Mybatis自动实现 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--接口写在这个目录中由mybatis来实现-->
<property name="basePackage" value="com.caicai.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 事务管理交给spring -->
<bean name="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- aop配置 -->
<tx:advice id="userTxAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="select*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pc" expression="execution(* com.caicai.dao.*.*(..))" />
<aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
</aop:config>
</beans>
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo
jdbc.username=root
jdbc.password=kami
六、Freemarker自定义标签的使用(可选)
假设对article表进行读取
id | title | content |
1 | hehe | 呵呵哒 |
2 | huanghuagn | 慌慌哒 |
假设要在模版页面上显示一片article,且想随时可修改成任意id的那篇文章而不是去修改数据库,此时可使用自定义标签,然后修改ftl中自定义标签的参数即可。
首先编写一个自定义标签类实现TemplateDirectiveModel接口:
package com.caicai.controller;
import java.io.IOException;
import java.util.Map;
import freemarker.core.Environment;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateNumberModel;
public class MyDirective implements TemplateDirectiveModel {
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
throws TemplateException, IOException {
Object paramValue = params.get("articleId"); // 参数起名为articleId
// Freemarker自定义标签不能直接识别传过来的数据类型参数,这里是number类型的处理
int id = 0;
if (paramValue instanceof TemplateNumberModel) {
id = ((TemplateNumberModel) paramValue).getAsNumber().intValue();
}
Article article = getArticleById(id); // 根据id去查询文章,具体实现方法省略
env.setVariable("article",DEFAULT_WRAPPER.wrap(article)); //freemarker老版本使用此方法处理自定义标签解析数据
body.render(env.getOut()); // 最后使用body.render(env.getOut())将数据交给模版页面
}
}
在访问文章的action中要把自定义标签加入到model中,否则无法解析
@RequestMapping(value = "/document/getArticle")
public String getArticle( Model root) throws Exception {
root.put("article_d", new ArticleDirective()); //把标签放到页面,我的标签名为article_d,方便区分数据,注意命名不要与变量名一样
return article;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<@article articleId = 1> <#-- 使用自定义标签,传入的参数与自定义标签类保持一致 -->
文章的标题是${article.title},文章的内容是${article.content}
</@article>
</body>
</html>
那么访问该action则页面输出结果:文章的标题是:...,文章的内容是...。如若要更改访问的article,修改ftl文件中的articleId为想要的文章id即可。