SpringMVC-Spring-MyBatis-Freemarker整合+源码下载

来源:互联网 发布:中企动力java面试 编辑:程序博客网 时间:2024/05/20 04:26

前言:之前看过很多大神写的SSM整合,但一直没亲自动手去这搞过,对于这三个框架的整合脑子中也是模模糊糊,今天决定去弄一下,加深一下自己对他们的印象,而且我也会把最常用的前端框架FreeMarker整合到一起,以及拦截器和过滤器的使用,小弟也是第一次整合这几个常用的框架,如有错误,敬请包涵和指出。

框架版本:Spring4.0, Mybatis3.2.0, Freemarker 2.3.16
数据库:Oracle11g
服务器:Tomcat7.0
开发工具:MyEclipse

第一步:创建名称为ssm的web项目,并导入所需jar,整个项目结构以及所需所有jar如下图所示:

这里写图片描述
WebRoot目录下:

第二部:建表(我这里使用PL/SQL操作)、创建序列、插入数据

create table USERINFO(  id        VARCHAR2(50) not null primary key,  name      VARCHAR2(50),  age       VARCHAR2(50),  loginname VARCHAR2(50),  password  VARCHAR2(50))
create sequence SEQ_IDminvalue 1maxvalue 99999start with 22increment by 1cache 20order;
insert into userInfo(id,name,age,loginName,password) values(seq_id.nextval,'超级管理员''26','admin','123456')

第三步:创建实体,映射接口及实现,相当于以前的dao层接口和dao层实现

package com.xujd.model;/** * 用户实体 * @ClassName User * @Description TODO * @author XuJD * @date 2017-6-6 */public class User{    private String id;    private String name;    private String age;    private String loginName;    private String password;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getAge() {        return age;    }    public void setAge(String age) {        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getLoginName() {        return loginName;    }    public void setLoginName(String loginName) {        this.loginName = loginName;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}
package com.xujd.mapper;import java.util.List;import com.xujd.model.User;public interface UserMapper {    void save(User op);    boolean update(User op);    boolean delete(int id);    User findById(int id);    List<User> findAll();    User login(User user);}
<?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"> <!--       namespace:必须与对应的UserMapper.java接口全类名一致      id:必须与对应接口的某个对应的方法名一致      -->  <mapper namespace="com.xujd.mapper.UserMapper" >    <sql id="UPDATE_USERINFO_ITEMS">        <trim prefix="set" suffixOverrides=",">            <if test="name!=null and name!=''">                name=#{name},            </if>            <if test="age!=null and age!=''">                age=#{age},            </if>            <if test="loginName!=null and loginName!=''">                loginName=#{loginName},            </if>            <if test="password!=null and password!=''">                password=#{password},            </if>        </trim>    </sql>    <insert id="save" parameterType="User" flushCache="true">        insert into userInfo(id,name,age,loginName,password)         values(seq_id.nextval,#{name},#{age},#{loginName},#{password})    </insert>    <update id="update" parameterType="User" flushCache="true">        update userInfo        <include refid="UPDATE_USERINFO_ITEMS"/>        where id=#{id}    </update>    <delete id="delete" parameterType="int" flushCache="true">        delete userInfo where id=#{id}    </delete>    <select id="findById" parameterType="int" resultType="User" useCache="true" >        select * from userInfo where id=#{id}    </select>    <select id="findAll" resultType="User" useCache="true">        select * from userInfo    </select>    <select id="login" resultType="User" parameterType="User" useCache="true">        select * from userInfo where loginName=#{loginName} and password=#{password}    </select></mapper>

第四步:Mybatis配置文件

<?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>    <!-- 实体类,简称 -设置别名 -->    <typeAliases>        <typeAlias alias="User" type="com.xujd.model.User" />    </typeAliases>    <!-- 实体接口映射资源 -->    <!--    说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,    因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml    -->    <mappers>        <mapper resource="com/xujd/mapper/UserMapper.xml" />    </mappers></configuration>  

第五步:SpringMVC配置文件

<?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:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-4.0.xsd    http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">    <!-- 开启注解 -->    <mvc:annotation-driven />    <mvc:default-servlet-handler />    <!-- 注解扫描包 -->    <context:component-scan base-package="com.xujd" />    <!--        配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd    -->    <mvc:resources mapping="/img/**" location="/img/" />    <mvc:resources mapping="/js/**" location="/js/" />    <mvc:resources mapping="/css/**" location="/css/" />    <mvc:resources mapping="/html/**" location="/html/" />    //配置拦截器    <mvc:interceptors>        <mvc:interceptor>            <!-- 需拦截的请求 -->            <mvc:mapping path="/bg/user/*"/>            <bean class="com.xujd.interceptor.LoginInterceptor"/>        </mvc:interceptor>    </mvc:interceptors>    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->    <!-- Jsp视图解析器-->      <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->        <property name="prefix" value="/jsp/" />        <property name="suffix" value=".jsp" />        <property name="viewClass"            value="org.springframework.web.servlet.view.JstlView" />        <property name="order" value="1" /><!--jsp设置为1,ftl设置为0,表示先找ftl,没有再找jsp -->    </bean>    <!-- FreeMarker视图解析器 -->      <bean id="viewResolverFtl" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">          <property name="order" value="0" />        <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>          <!-- 配置freeMarker的模板路径 -->      <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">          <!-- <property name="templateLoaderPaths" > ftl多路径配置            <list>                <value>/ftl/user/</value>                <value>/ftl/test/</value>            </list>         </property> -->        <property name="templateLoaderPath" value="/ftl/"/>        <property name="freemarkerVariables">              <map>                  <entry key="xml_escape" value-ref="fmXmlEscape" />              </map>          </property>          <property name="defaultEncoding" value="utf-8" />           <property name="freemarkerSettings">  <!-- 设置FreeMarker环境属性 -->            <props>                  <prop key="template_update_delay">0</prop><!--刷新模板的周期,单位为秒 -->                <prop key="default_encoding">UTF-8</prop>  <!--模板的编码格式 -->                <prop key="locale">UTF-8</prop><!-- 本地化设置 -->                <prop key="number_format">0.##########</prop>                  <prop key="date_format">yyyy-MM-dd</prop>                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>                  <prop key="classic_compatible">true</prop>                  <prop key="template_exception_handler">ignore</prop>              </props>          </property>      </bean>     <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/> </beans>

第六步:Spring-Common配置文件(Spring、Mybatis整合)

<?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:tx="http://www.springframework.org/schema/tx"      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/tx          http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">     <!-- 注册jdbc属性文件(1) -->    <!-- <context:annotation-config/>    <context:property-placeholder location="classpath:db.properties"/>  -->    <!-- 1. 数据源 : DriverManagerDataSource -->      <bean id="dataSource"          class="org.springframework.jdbc.datasource.DriverManagerDataSource">          <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />          <property name="url" value="jdbc:oracle:thin:@192.168.2.17:1521:yx" />          <property name="username" value="ts_yx" />          <property name="password" value="ts_yx" />      </bean>    <!--          2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源                MyBatis定义数据源,同意加载配置      -->      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">          <property name="dataSource" ref="dataSource"></property>          <property name="configLocation" value="classpath:config/mybatis-config.xml" />       </bean>      <!--          3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory          basePackage:指定sql映射文件/接口所在的包(自动扫描)      -->      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">          <property name="basePackage" value="com.xujd.mapper"></property>          <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>      </bean>          <!--         4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源     -->      <bean id="txManager"          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">          <property name="dataSource" ref="dataSource"></property>      </bean>      <!-- 5. 使用声明式事务           transaction-manager:引用上面定义的事务管理器       -->      <tx:annotation-driven transaction-manager="txManager" />  </beans>

第七步: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">    <!-- 设置Spring容器加载所有的配置文件的路径 -->    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath*:config/spring-*.xml</param-value>    </context-param>    <!-- 配置SpringMVC核心控制器 -->    <servlet>        <servlet-name>springMVC</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <!-- 配置初始配置化文件,前面contextConfigLocation看情况二选一 -->            <!-- init-param 节点必须在 load-on-startup 节点以上 -->        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath*:config/spring-mvc.xml</param-value>        </init-param>        <!-- 启动加载一次 -->          <load-on-startup>1</load-on-startup>    </servlet>    <!--为DispatcherServlet建立映射 -->    <servlet-mapping>        <servlet-name>springMVC</servlet-name>        <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->        <url-pattern>/</url-pattern>    </servlet-mapping>    <!-- 加载Spring容器配置 -->    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <!-- 防止Spring内存溢出监听器 -->    <listener>        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>    </listener>    <!-- 解决工程编码过滤器 -->    <filter>        <filter-name>encodingFilter</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>encodingFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <welcome-file-list>        <welcome-file>/index.ftl</welcome-file>    </welcome-file-list>    <!-- session有效时间,单位分钟 -->    <session-config>        <session-timeout>30</session-timeout>    </session-config>    <!--    过滤器配置 -->     <filter>        <filter-name>backFilter</filter-name>        <filter-class>com.xujd.filter.BackFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>backFilter</filter-name>        <url-pattern>/bg/*</url-pattern>//需要过滤的请求    </filter-mapping> </web-app>

第八步:过滤器和拦截器比较简单,在配置文件中有详细说明,下面看效果图吧,界面很low,可以忽视

这里写图片描述
这里写图片描述
这里写图片描述

在这里,拦截器和过滤器的作用是作为一个登入校验,没有登入的情况下访问系统会直接跳转到登入页面

总结:这几个框架整合还是相对简单的,虽然当中遇到一些问题,但是解决了,其他代码我就不一一贴出来了,我会把源码贴出来。

源码下载:SpringMVC-Spring-Mybatis-Freemarker

下一篇文章介绍:在这篇博文的基础上集成dubbo和zookeeper,做一个简单的分布式入门