搭建Spring、Spring MVC、Mybatis和Freemarker
1、pom文件
<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.candle</groupId> <artifactId>home-finance-sample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>home-finance-sample Maven Webapp</name> <url>http://maven.apache.org</url> <build> <finalName>home-finance-sample</finalName> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- spring jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>3.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.6.RELEASE</version> </dependency> <!-- spring mvc jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.6.RELEASE</version> </dependency> <!-- mybatis jar --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.4</version> </dependency> <!-- mybatis-spring jar --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- mysql-connector-java jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.28</version> </dependency> <!-- 数据库连接池 jar --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <!-- log jar --> <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.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <!-- jsp Template jar --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency> <!-- apache servlet api jar --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>servlet-api</artifactId> <version>6.0.37</version> </dependency> </dependencies> </project>
2、web.xml配置文件
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>Archetype Created Web Application</display-name> <!-- Spring 配置文件路径,此处可将Spring MVC的相关配置内容配置到Spring的配置文件applicationContext.xml中,共享同一个配置文件即可 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <!-- Spring 监听器 配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- 字符集 过滤器 --> <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-8</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> <!-- Spring mvc 配置,配置文件名称默认为{servlet-name}-servlet.xml,路径默认在/WEB-INF/下 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3、Spring MVC 配置文件,路径在/WEB-INF/下,springmvc-servlet.xml,里面包括freemarker的配置内容
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" > <context:component-scan base-package="com.hf.controller" /> <mvc:annotation-driven /> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/views" /> <property name="suffix" value=".jsp" /> </bean> --> <mvc:resources mapping="/**" location="/"/> <!-- ===================================================== --> <!-- ViewResolver For FreeMarker --> <!-- ===================================================== --> <bean id="freemarkerResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="order" value="1" /> <property name="suffix" value=".ftl" /> <property name="contentType" value="text/html;charset=utf-8" /> <property name="viewClass"> <value>org.springframework.web.servlet.view.freemarker.FreeMarkerView</value> </property> </bean> <!-- ===================================================== --> <!-- ViewResolver For FreeMarkerConfigurer --> <!-- ===================================================== --> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath"> <value>/views/</value> </property> <property name="freemarkerSettings"><!-- 设置FreeMarker环境属性 --> <props> <prop key="template_update_delay">5</prop><!--刷新模板的周期,单位为秒 --> <prop key="default_encoding">UTF-8</prop><!--模板的编码格式 --> <prop key="locale">UTF-8</prop><!-- 本地化设置 --> <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop> <prop key="time_format">HH:mm:ss</prop> <prop key="number_format">0.####</prop> <prop key="boolean_format">true,false</prop> <prop key="whitespace_stripping">true</prop> <prop key="tag_syntax">auto_detect</prop> <prop key="url_escaping_charset">UTF-8</prop> </props> </property> </bean> </beans>
4、applicationContext.xml,此处省略dataSource.properties配置的数据库连接的内容
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 扫描com.hf包里下的所有class文件,配置注解的类全都装入容器中进行管理 --> <context:component-scan base-package="com.hf" /> <!-- 添加注解驱动 --> <mvc:annotation-driven /> <!-- 引入jdbc配置文件 --> <context:property-placeholder location="classpath:dataSource.properties" /> <!--创建jdbc数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> <!-- 配置事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 创建SqlSessionFactory,并指定数据源 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <!-- Mapper文件扫描配置工具,Spring将自动扫描对应配置路径下的Mapper --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="classpath:" /> </bean> <!-- MapperFactoryBean 创建的代理类实现了IUserDAO接口,并且注入到应用程序中,这样不用写实现类 --> <bean id="userDAO" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.hf.idao.IUserDAO" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> </beans>
5、Mybatis的相关配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTDConfig 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- 配置映射文件 --> <configuration> <mappers> <!--映射文件--> <mapper resource="user.xml"/> </mappers> </configuration>
映射文件,user.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.hf.idao.IUserDAO"> <resultMap type="com.hf.model.UserDo" id="UserDo" autoMapping="true"> <id property="id" column="id"/> <result property="username" column="username"/> <result property="password" column="password"/> </resultMap> <select id="findAllUser" resultMap="UserDo"> select * from w_user </select> </mapper>
6、业务代码
model层
package com.hf.model; import java.io.Serializable; public class UserDo implements Serializable { private int id ; private String username ; private String password ; 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 String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
dao层
package com.hf.idao; import java.util.List; import com.hf.model.UserDo; public interface IUserDAO { public List<UserDo> findAllUser() ; }
service层
package com.hf.iservice; import java.util.List; import com.hf.model.UserDo; public interface IUserService { public List<UserDo> findAllUser() ; }
package com.hf.service; import java.util.List; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hf.idao.IUserDAO; import com.hf.iservice.IUserService; import com.hf.model.UserDo; @Service("userService") public class UserService implements IUserService { @Autowired private IUserDAO userDAO ; @Override public List<UserDo> findAllUser() { return userDAO.findAllUser(); } }
controller层
package com.hf.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.hf.iservice.IUserService; import com.hf.model.UserDo; @Controller public class UserController { @Autowired private IUserService userService ; @RequestMapping("/User/helloUser") public String helloUser(ModelMap modelMap) { List<UserDo> list = this.userService.findAllUser(); modelMap.addAttribute("userDo", list) ; return "/user_list"; } }
views层文件user_list.ftl:
<#setting classic_compatible=true> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>User List</title> <style type="text/css"> <!-- .STYLE1 { font-family: Arial, Helvetica, sans-serif; font-weight: bold; font-size: 36px; color: #FF0000; } .STYLE13 {font-size: 24} .STYLE15 {font-family: Arial, Helvetica, sans-serif; font-size: 24px; } --> </style> </head> <body> <table width="1500" height="600" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="500" height="200"> </td> <td width="500" height="200" align="center" valign="middle"><div align="center"><span class="STYLE1">User List </span></div></td> <td width="500" height="200"> </td> </tr> <tr> <td width="500" height="200"> </td> <td width="500" height="200"><table width="500" height="200" border="1" cellpadding="0" cellspacing="0"> <tr> <td width="160" height="65" align="center" valign="middle"><span class="STYLE15">ID</span></td> <td width="160" height="65" align="center" valign="middle"><span class="STYLE15">Username</span></td> <td width="160" height="65" align="center" valign="middle"><span class="STYLE15">Password</span></td> </tr> <#list userDo as user> <tr> <td width="160" height="65" align="center" valign="middle"><span class="STYLE15">${user.id}</span></td> <td width="160" height="65" align="center" valign="middle"><span class="STYLE15">${user.username}</span></td> <td width="160" height="65" align="center" valign="middle"><span class="STYLE15">${user.password}</span></td> </tr> </#list> </table></td> <td width="500" height="200"> </td> </tr> <tr> <td width="500" height="200"> </td> <td width="500" height="200"> </td> <td width="500" height="200"> </td> </tr> </table> </body> </html>