Spring MVC+mybatis 环境搭建,总结

时间:2021-10-16 23:17:17

1、配置WEB.XML

 <!-- 监听spring上下文容器 -->  
    <listener>  
        <listener-class>  
            org.springframework.web.context.ContextLoaderListener  
        </listener-class>  
    </listener>  
      
    <!-- 加载spring的xml配置文件到 spring的上下文容器中 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:*-context.xml</param-value>  
    </context-param>  
      
    <!-- 配置Spring MVC DispatcherServlet -->  
    <servlet>  
        <servlet-name>MVC</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <!-- 初始化参数 -->  
        <init-param>  
            <!-- 加载SpringMVC的xml到 spring的上下文容器中 -->  
            <param-name>contextConfigLocation</param-name>  
            <param-value>  
                /WEB-INF/classes/mvc-context.xml  
            </param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
  
    <!-- 配置DispatcherServlet所需要拦截的 url -->  
    <servlet-mapping>  
        <servlet-name>MVC</servlet-name>  
        <url-pattern>*.do</url-pattern>  
    </servlet-mapping>  
  
    <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
    </welcome-file-list>  

2.MVC配置文件主要是实现后台与前台视图的映射

<context:component-scan base-package="com.wg.*" />


<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/page/" />
<property name="suffix" value=".jsp" />
</bean>

3.mybatis配置文件,主要是实现模型类与数据库映射类的配置

<configuration>
<typeAliases>
<package name="com.wg.bean" />
</typeAliases>
<mappers>
<mapper resource="com/wg/bean/UserMapper.xml" />
</mappers>
</configuration> 

4、数据源配置文件

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property> 
         <property name="url"><value>jdbc:oracle:thin:@127.0.0.1:1521:ORCL</value></property> 
         <property name="username"><value>HUHU</value></property> 
         <property name="password"><value>123456</value></property>
</bean>


<!-- 创建SqlSessionFactory,同时指定数据源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>

5.接口与mybatis,spring映射配置

<!-- 用户Dao -->
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
    <property name="mapperInterface" value="com.wg.dao.UserDao" />  
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
</bean>