今天说说搭建项目,使用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` ) NOT NULL AUTO_INCREMENT, `demoname` ) DEFAULT NULL, PRIMARY KEY (`demoid`) ) ENGINE 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>
项目整体结构如下图
运行过后,结果如下
自此,项目搭建完成了。项目已经上传到github上,地址为:https://github.com/fudexue/Demo
希望能一起交流学习java,java技术交流QQ群:485731690