spring整合freemarker

时间:2021-11-24 12:58:12

一、配置maven

<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.</modelVersion>
<groupId>com.booway</groupId>
<artifactId>booway-springFreemarker</artifactId>
<packaging>war</packaging>
<version>0.0.-SNAPSHOT</version>
<name>booway-springFreemarker Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 集中定义依赖版本号 -->
<properties>
<junit.version>4.9</junit.version>
<spring.version>4.2..RELEASE</spring.version>
<mybatis.version>3.4.</mybatis.version>
<mybatis.spring.version>1.3.</mybatis.spring.version>
<mysql.version>6.0.</mysql.version>
<slf4j.version>1.7.</slf4j.version>
<druid.version>1.0.</druid.version>
<jstl.version>1.2</jstl.version>
<servlet-api.version>3.1.</servlet-api.version>
<standard.version>1.1.</standard.version>
<freemarker.version>2.3.</freemarker.version>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- 日志处理 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!-- MySql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
<version>${spring.version}</version>
</dependency>
<!-- JSP相关 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency> <dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${standard.version}</version>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency> </dependencies> <build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-</encoding>
</configuration>
</plugin>
<!-- 配置Tomcat插件 -->
<plugin>
<!-- 命令为clean tomcat7:run -->
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<port></port>
<path>/</path>
</configuration>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>

二、项目大致结构

spring整合freemarker

三、配置/booway-springFreemarker/src/main/resources/mybatis/mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration>
<!-- 设置全局配置 -->
<settings>
<!-- 使用主键自增策略 -->
<setting name="useGeneratedKeys" value="true" />
<!-- select name as title from user 用于识别别名, -->
<setting name="useColumnLabel" value="true" />
<!-- 开启驼峰命名转换,如:table中(create_time)->entity(createTime)这样在sql语句中就不需要使用as来显式的去定义别名 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings> </configuration>

四、配置/booway-springFreemarker/src/main/resources/spring/springContext-dao.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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:property-placeholder location="classpath:resources/*.properties" /> <!-- 数据源配置, 使用 Druid 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" /> <!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="" />
<property name="minIdle" value="" />
<property name="maxActive" value="" /> <!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
<!-- 定义别名,如果使用了mybatis的逆向工程,无需这个,因为配置文件是自动生成的,不用你写。 -->
<property name="typeAliasesPackage" value="com.booway.pojo"></property> <property name="mapperLocations" value="classpath:mybatis/mappers/*.xml"></property>
<!-- 配置映射文件的位置,如果配置文件与mapper接口在同一个位置,可以不写 -->
<!-- <property name="mapperLocations">
<array>
<value>classpath:mybatis/mappers/User.xml</value>
</array>
</property> --> </bean> <!-- 将mybatis实现的接口注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="com.booway.mapper"></property>
</bean> </beans>

五、配置/booway-springFreemarker/src/main/resources/spring/springContext-service.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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 扫描这个包下以及子包的内容 -->
<context:component-scan base-package="com.booway.service"></context:component-scan> <!-- <bean id="userServiceImpl" class="com.booway.serviceImpl.UserServiceImpl">
</bean> --> </beans>

六、java代码

1、pojo类/booway-springFreemarker/src/main/java/com/booway/pojo/User.java

package com.booway.pojo;

import java.util.Date;

public class User {

    private int id;

    private String username;

    private int age;

    private Date birthday;

    public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} }

2、com.booway.controller.UserController

package com.booway.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import com.booway.pojo.User;
import com.booway.service.UserService; @Controller
public class UserController {
@Resource(name="userServiceImpl")
private UserService userService; @RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.TEXT_HTML_VALUE + ";charset=utf-8")
public String queryUsers(Model model) {
List<User> users = userService.getAllUsers();
model.addAttribute("users", users); return "test.ftl";
} }

3、com.booway.mapper.UserMapper

package com.booway.mapper;

import java.util.List;

import com.booway.pojo.User;

public interface UserMapper {

    List<User> getAllUsers();

}

4、com.booway.service.UserService

package com.booway.service;

import java.util.List;

import com.booway.pojo.User;

public interface UserService {

    List<User> getAllUsers();

}

5、com.booway.service.serviceImpl.UserServiceImpl

package com.booway.service.serviceImpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.booway.mapper.UserMapper;
import com.booway.pojo.User;
import com.booway.service.UserService; @Service
public class UserServiceImpl implements UserService { @Autowired
private UserMapper userMapper; public UserServiceImpl() { } @Override
public List<User> getAllUsers() {
List<User> users = userMapper.getAllUsers(); return users;
} }

七、配置/booway-springFreemarker/src/main/resources/spring/springContext-transaction.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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.booway.service..*.*(..))" />
</aop:config> <tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- 传播行为REQUIRED时,有实物就是用但钱事务,没有就自动创建一个新的事务 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<!-- SUPPORTS有事务就支持事务,没有就没有 -->
<tx:method name="*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice> <bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> </beans>

、配置/booway-springFreemarker/src/main/resources/spring/springMVC-freemarker.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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- freemarker begin -->
<!-- 配置Freemarker属性文件路径 -->
<bean id="freemarkerConfiguration"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:resources/freemarker.properties" />
</bean>
<!-- 配置freeMarker模板加载地址 -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!-- 视图解析器会在/WEB-INF/ftl/路径下扫描视图文件 -->
<property name="templateLoaderPath" value="/WEB-INF/ftls/" />
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape" />
</map>
</property>
</bean>
<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />
<!-- 配置freeMarker视图解析器 -->
<bean id="freemakerViewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
<!-- 扫描路径內所有以ftl结尾的文件 -->
<property name="viewNames">
<array>
<value>*.ftl</value>
</array>
</property>
<property name="contentType" value="text/html; charset=UTF-8" />
<property name="cache" value="true" />
<!-- <property name="exposeRequestAttributes" value="true" /> -->
<!-- <property name="exposeSessionAttributes" value="true" /> -->
<!-- <property name="exposeSpringMacroHelpers" value="true" /> -->
<!-- <property name="requestContextAttribute" value="request" /> -->
<!-- 给视图解析器配置优先级 -->
<property name="order" value="" />
</bean>
<!-- freemarker end -->
</beans>

九、配置/booway-springFreemarker/src/main/resources/spring/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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.booway.controller"></context:component-scan>
<!-- 定义时间转换格式 -->
<!-- <bean id="formattingConversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<bean class="com.booway.convert.DateFormatter">
<constructor-arg name="datePattern" value="yyyy-MM-dd"></constructor-arg>
</bean>
</set>
</property>
</bean> --> <!-- 开启mvc注解,可使用@DateTimeFormat,@NumberFormat -->
<!-- <mvc:annotation-driven conversion-service="formattingConversionService"></mvc:annotation-driven> -->
<mvc:annotation-driven></mvc:annotation-driven> <mvc:resources location="/WEB-INF/css/" mapping="/css/**"></mvc:resources> <bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
<!-- <property name="order" value="" /> -->
</bean> </beans>

十、配置web.xml

<?xml version="1.0" encoding="utf-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true"> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springContext-*.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <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/springMVC-*.xml</param-value>
</init-param>
<load-on-startup></load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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-</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>

十一、配置/booway-springFreemarker/src/main/resources/log4j.properties

log4j.rootLogger=DEBUG,A1
log4j.logger.org.mybatis = DEBUG
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

十二、配置/booway-springFreemarker/src/main/resources/resources/jdbc.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

十三、配置/booway-springFreemarker/src/main/resources/resources/freemarker.properties

tag_syntax=auto_detect
template_update_delay=
default_encoding=UTF-
output_encoding=UTF-
locale=zh_CN
date_format=yyyy-MM-dd
time_format=HH:mm:ss
datetime_format=yyyy-MM-dd HH:mm:ss

十四、ftl模板文件

/booway-springFreemarker/src/main/webapp/WEB-INF/ftls/test.ftl

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户列表</title>
</head>
<body>
<table align='center' border=''>
<caption>用户列表</caption>
<tbody>
<tr>
<th>ID</th>
<th>name</th>
<th>age</th>
<th>birthday</th>
</tr>
<#list users as user>
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.age}</td>
<td>${user.birthday?string("yyyy-MM-dd HH:mm:ss")}</td>
</tr> </#list>
<tbody>
</table>
</body>
</html>