freemarker + spring mvc + spring + mybatis + mysql + maven项目搭建

今天说说搭建项目,使用freemarker + spring mvc + spring + mybatis + mysql + maven搭建web项目。

先假设您已经配置好eclipse的maven,创建好一个maven的web项目--Demo。我这里是jdk1.7,tomcat7。

修改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>com.service</groupId>
    <artifactId>Demo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Demo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>4.0.7.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <!-- 第三方依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.20</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.7</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>Demo</finalName>
    </build>
</project>

接下来配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">

    <display-name>Demo</display-name>

    <!-- 定义Spring配置文件位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/spring/*-context.xml</param-value>
    </context-param>

    <!-- Spring 配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- CharacterEncodingFilter configuration -->
    <filter>
        <display-name>CharacterEncodingFilter</display-name>
        <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>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <!-- Spring MVC 框架 -->
    <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:config/spring/mvc-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <!--Spring log4j Config loader -->
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>

    <welcome-file-list>
        <welcome-file>/index.html</welcome-file>
    </welcome-file-list>

</web-app>

首先配置一下log4j,在src/main/resource/包下新建文件log4j.properties

#
# Log4J Settings for log4j 1.2.x (via jakarta-commons-logging)
#
# The five logging levels used by Log are (in order):
#
#   1. DEBUG (the least serious)
#   2. INFO
#   3. WARN
#   4. ERROR
#   5. FATAL (the most serious)
# Set root logger level to INFO and append to stdout
log4j.rootLogger=INFO,stdout,file

## test print console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%p]%-d{yyyy-MM-dd HH\:mm\:ss}[%c\:%L] %m%n 

log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=/logs/demo.log
log4j.appender.file.DatePattern=‘.‘yyyy-MM-dd
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p]%-d{yyyy-MM-dd HH\:mm\:ss}[%c\:%L] %m%n 

接下来配置sping,按照web.xml的配置,在src/main/resource/包下新建目录config,在config目录下新建spring目录,在spring目录下新建文件application-context.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: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/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    <!-- 注解探测器 -->
    <context:component-scan base-package="com.service" />
    <!-- 读取配置文件 -->
    <context:property-placeholder
        location="classpath:config/base/datasource.properties"
        ignore-unresolvable="true" />
    <!-- 数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <!-- 指定连接数据库的驱动 -->
        <property name="driverClass" value="${database.driverClassName}" />
        <property name="jdbcUrl" value="${database.url}" />
        <property name="user" value="${database.username}" />
        <property name="password" value="${database.password}" />
        <!-- 指定连接数据库连接池的最大连接数 -->
        <property name="maxPoolSize" value="${pool.maxPoolSize}" />
        <!-- 指定连接数据库连接池的最小连接数 -->
        <property name="minPoolSize" value="${pool.minPoolSize}" />
        <!-- 指定连接数据库连接池的初始化连接数 -->
        <property name="initialPoolSize" value="${pool.initialPoolSize}" />
        <!-- 指定连接数据库连接池的连接的最大空闲时间 -->
        <property name="maxIdleTime" value="${pool.maxIdleTime}" />
        <!-- 连接关闭时默认将所有未提交的操作回滚。默认:false -->
        <property name="autoCommitOnClose" value="${pool.autoCommitOnClose}" />
        <!-- 当连接用完时,等待获取新的连接,超时后将抛出SQLException,如果设置为0,则无限等待,单位毫秒,默认:0 -->
        <property name="checkoutTimeout" value="${pool.checkoutTimeout}" />
        <property name="acquireIncrement" value="${pool.acquireIncrement}" />
        <property name="acquireRetryAttempts" value="${pool.acquireRetryAttempts}" />
    </bean>
    <!-- factory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="mapperLocations" value="classpath:com/service/dao/*Mapper.xml" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="annotationClass" value="org.springframework.stereotype.Repository" />
        <property name="basePackage" value="com.service.dao" />
    </bean>

</beans>

在同样这个目录下配置spring mvc,新建文件mvc-context.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="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/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
    <!-- 框架控制层 controller -->
    <!-- 注解探测器 -->
    <context:component-scan base-package="com.service.controller" />
    <mvc:annotation-driven />

    <!-- freemarker做为视图 -->
    <bean id="freemarkerConfig"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <!--视图资源位置 -->
        <property name="templateLoaderPath" value="/WEB-INF/page/" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop><!-- 模板更新延时 -->
                <prop key="classic_compatible">true</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="number_format">0.######</prop>
            </props>
        </property>
        <!-- 全局变量部分 -->
        <property name="freemarkerVariables">
            <map>
                <entry key="BasePath" value="${basePathWebUrl}" />
                <entry key="resourcePath" value="${resourcePathWebSite}" />
                <entry key="jsResourcePath" value="${jsPathWebSite}" />
            </map>
        </property>
    </bean>
    <!-- Freemarker配置 -->
    <bean id="ftlviewResolver"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
        <property name="contentType" value="text/html;charset=UTF-8" />
        <property name="cache" value="true" />
        <property name="suffix" value=".html"></property>
    </bean>
</beans>

同样在src/main/resource/config/目录下,新建base目录,新建一个数据库配置文件datasource.properties

#Dstandard_test
database.driverClassName=com.mysql.jdbc.Driver
database.url=jdbc:mysql://127.0.0.1/demo?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull
database.username=root
database.password=123456
pool.maxPoolSize=25
pool.minPoolSize=3
pool.initialPoolSize=3
pool.maxIdleTime=180
pool.checkoutTimeout=10000
pool.acquireIncrement=3
pool.acquireRetryAttempts=10
pool.autoCommitOnClose=true

在本地安装好mysql数据库,创建一个数据库demo,新建一张表t_demo,两个字段demoid,demoname,并插入几条数据

CREATE TABLE `t_demo` (
  `demoid` int(11) NOT NULL AUTO_INCREMENT,
  `demoname` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`demoid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

在src/main/java/目录下新建包com.service.controller用来写控制器层代码。新建com.service.service写service层代码,com.service.dao写dao层代码,com.service.entity写实体类,代码分别如下:DemoController.java

package com.service.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.service.entity.DemoEntity;
import com.service.service.DemoService;

@Controller
public class DemoController {
    public static final Logger logger = Logger.getLogger(DemoController.class);
    @Resource
    private DemoService demoService;

    /**
     * 首页
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/index.html")
    public String index(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        logger.info(" " + " " + " 获取到数据");
        List<DemoEntity> demoList = demoService.getDemoList();
        model.put("demoList", demoList);
        return "index";
    }
}

DemoService.java接口

package com.service.service;

import java.util.List;

import com.service.entity.DemoEntity;

public interface DemoService {
    public List<DemoEntity> getDemoList();
}

DemoServiceImpl.java实现类

package com.service.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.service.dao.DemoDao;
import com.service.entity.DemoEntity;
@Service
public class DemoServiceImpl implements DemoService {
    public static final Logger logger = Logger.getLogger(DemoServiceImpl.class);
    @Resource
    private DemoDao demoDao;
    @Override
    public List<DemoEntity> getDemoList() {
        logger.info("service test");
        List<DemoEntity> demoList = demoDao.getDemoList();
        return demoList;
    }
}

DemoDao.java接口

package com.service.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.service.entity.DemoEntity;

@Repository
public interface DemoDao {

    public List<DemoEntity> getDemoList();
}

DemoEntity.java实体类

package com.service.entity;

public class DemoEntity {

    private String demoId;
    private String demoName;
    public String getDemoId() {
        return demoId;
    }
    public void setDemoId(String demoId) {
        this.demoId = demoId;
    }
    public String getDemoName() {
        return demoName;
    }
    public void setDemoName(String demoName) {
        this.demoName = demoName;
    }
}

在src/main/resource下新建目录com,在com目录下新建目录service,再在service下新建目录dao,然后就新建文件DemoMapper.xml,代码如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.service.dao.DemoDao">
    <sql id="tableName">t_demo</sql>
    <resultMap id="BaseResultMap" type="com.service.entity.DemoEntity">
        <id column="demoid" property="demoId" />
        <result column="demoname" property="demoName" />
    </resultMap>

    <!-- 统计总问题数 -->
    <select id="getDemoList" resultMap="BaseResultMap">
        select t1.demoid,t1.demoname
        from t_demo t1
        order by t1.demoid desc
    </select>
</mapper>

到此,现在需要完成数据的展示部分,在WEB-INF目录下新建文件夹page,在page下新建文件index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    this is freemarker html! <br>
    <#if demoList??&&(demoList?size>0)>
        <#list demoList as list>
            ${list.demoId}--${list.demoName}<br>
        </#list>
    <#else> 暂无 </#if>
</body>
</html>

项目整体结构如下图

运行过后,结果如下

自此,项目搭建完成了。

希望能一起交流学习java,java技术交流QQ群:485731690

时间: 2024-10-11 06:15:09

freemarker + spring mvc + spring + mybatis + mysql + maven项目搭建的相关文章

IDEA下创建Maven项目,并整合使用Spring、Spring MVC、Mybatis框架

项目创建 本项目使用的是IDEA 2016创建.项目使用Spring 4.2.6,Mybatis3.4.0,Tomcat使用的是Tomcat8,数据库为MySQL. 首先电脑安装Maven,接着打开IDEA新建一个project,选择Maven,选择图中所选项,下一步. 填写好GroupId和ArtifactId,GroupId在公司中一般都是域名的逆序,ArtifactId用来标明该项目是用来做什么的,接着下一步. 添加一个archetypeCatalog,值为internal可以加速项目的创

Spring mvc+ maven + MyBatis + Oracle + IDEA 项目搭建 - framework 进阶中(一)

原文链接 http://blog.csdn.net/qq184377902/article/details/51493642 结合自身情况加以修改搭建的框架,记录以防备忘,方便日后学习参考. Before building the project framework  ... 项目环境 IntelliJ IDEA 2016.1.2.JDK 1.8.0_31.Apache-maven-3.5.0.Tomcat-9.0.0.M11 Maven项目搭建 自行百度 .. Build project fr

Spring mvc整合mybatis基于mysql数据库实现用户增删改查及其分页显示的完整入门实例【转】

Spring mvc整合mybatis例子, 基于mysql数据库实现对用户的增.删.改.查,及分页显示的完整例子. 查询显示用户 添加用户 更新用户 官方验证: 项目截图 必须修改applicationContext.xml中mysql的配置为本地的,否则启动失败. 另外jar包多一个ehcache.jar无关紧要,删除即可. 1. 使用阿里巴巴Druid连接池(高效.功能强大.可扩展性好的数据库连接池.监控数据库访问性能.支持Common-Logging.Log4j和JdkLog,监控数据库

SSM(Spring MVC +Spring+Mybatis)整合——maven工程

所谓的SSM 其实就是Spring MVC下整合mybatis. 具体的定义网络上都有,很详细. 这里只说项目的搭建步骤. 第一步 新建maven工程 工程目录如下: 配置pom.xml文件,引入所需的jar包 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=&q

Spring、Spring MVC、MyBatis

Spring.Spring MVC.MyBatis整合文件配置详解 使用SSM框架做了几个小项目了,感觉还不错是时候总结一下了.先总结一下SSM整合的文件配置.其实具体的用法最好还是看官方文档. Spring:http://spring.io/docs MyBatis:http://mybatis.github.io/mybatis-3/ 基本的组织结构和用法就不说了,前面的博客和官方文档上都非常的全面.jar包可以使用Maven来组织管理.来看配置文件. web.xml的配置         

SSM(spring mvc+spring+Mybatis)框架整合

最近用Idea开发,idea是一款综合的相对较新的Java IDE.Idea支持很多整合功能,我觉得挺好用的.Idea可以校正xml,支持jsp的调试.最让我喜欢的是,写spring配置文件的时候,写的一些路径都可以自己找到.classpath自己有代码的提示,超级的智能. 环境配置 在整合框架之前,先配置一下JER运行环境,配置maven仓库. 1.File--ProjectStructure--Project--New- 选择jdk的安装环境 2.File--Settings--Maven-

SSM 即所谓的 Spring MVC + Spring + MyBatis 整合开发。

SSM 即所谓的 Spring MVC + Spring + MyBatis 整合开发.是目前企业开发比较流行的架构.代替了之前的SSH(Struts + Spring + Hibernate) 计划的架构组合 Sping MVC + Spring + MyBatis(非Ajax版) Sping MVC + Spring + MyBatis(Ajax版) Sping MVC + Spring + MyBatis(Ajax版 + JavaConfig) Spring Boot + MyBatis

Extjs5.0从入门到实战开发信息管理系统(Extjs基础、Extjs5新特性、Spring、Spring mvc、Mybatis)视频教程

Extjs5.0从入门到实战开发信息管理系统(Extjs基础.Extjs5新特性.Spring.Spring mvc.Mybatis)视频教程下载   联系QQ:1026270010 Extjs作为一款优秀的JS前端开发框架以其良好的架构.丰富的UI组件库.完善的文档和社区支持等诸多优点拥有广泛的市场应用空间,开发人员无需过多的关注HTML.CSS甚至各种常用JS算法,只需把精力放在业务逻辑上,利用各种组件的相互组合调用便可轻松而高效的开发出系统的前端页面. Extjs5在之前版本的基础上又推出

ssm(spring,spring mvc,mybatis)框架

ssm框架各个技术的职责 spring :spring是一个IOC DI AOP的 容器类框架 spring mvc:spring mvc 是一个mvc框架 mybatis:是一个orm的持久层框架 一般web项目的架构: jsp界面 ===> 控制层(Controller)== >业务逻辑层(Service)==>持久化层(dao)== >数据库层(Database) spring 框架是一个容器,作用在所有层. spring mvc 主要作用在控制层 mybatis主要作用在持