1.创建web项目 导入jia包
在spring基础jar包中新增
1.mybatis-x.x.x.x.jar
2.mybatis-spring-x.x.x.jar
3.mysql-conector-java.jar
2.配置web.xml文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
1.在context-param初始化参数,查找applicationContext.xml文件的位置
(默认去WEB-INF下查找applicationContext.xml)
2.配置监听器
在listener中加载org.springframeWork.web.context.ContextLoaderListener
web.xml中的contextConfigLocation在spring中的作用
3.配置applicationContext.xml
在src目录下创建applicationContext.xml(路径与刚才web.xml中context-param标签中的一致
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName"
>
</beans>
1.把mybatis-config.xml中的配置放到appliactionContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName"
>
<!-- 引入外部文件 -->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 创建dataScoure对象 -->
<bean id="dataScoure" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/music"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
<!-- 创建sessionFactory工厂 -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataScoure"></property>
<!-- mybatis-config文件中的实体类名简写 -->
<property name="typeAliasesPackage" value="com.it.pojo" />
</bean>
<!-- 创建configurer对象 把输出封装到里面-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 引入mapper映射文件-->
<property name="basePackage" value="com.it.mapper"></property>
<property name="sqlSessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 创建biz类 自动装载userMapper类 -->
<bean id="userbiz" class="com.it.biz.impl.UserBizImpl">
<property name="userMapper" ref="userMapper"></property>
</bean>
</beans>
4.创建pojo,dao,biz
其他代码和往常一样 但是在UserBizImpl中只需要写一个 private UserMapper userMapper 就可以调用,在appactionContext.xml文件中自动实例化UserMapper类。( 需要注意的是:UserMapper类的类名必须为userMapper 这种规范命名规则 )
5.编写Servlet类
在init方法里获取ApplocationContext,实例化一个userbiz类。接下来就可以在doPost/doGet方法中调用biz类的方法进行页面跳转