项目结构
web.xml(写在web-app标签内)
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 这个地方是配置Springmvc的路径classpath就是代表src的意思 -->
<param-value>classpath:config/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 设置编码格式 -->
<filter>
<filter-name>characterEncoding</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>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 使用context注释 -->
<context:annotation-config />
<!-- 扫描需要注释的包 -->
<context:component-scan
base-package="com.ly" />
<!-- 开启SpringMVC注解驱动 -->
<mvc:annotation-driven />
<!-- 静态资源默认servlet配置-->
<mvc:default-servlet-handler />
<!-- 连接数据库sqlserver(也可连接其他换成对应的url,username,password,driverClassName即可) -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- perpleinfo是数据库的名称 -->
<property name="url"
value="jdbc:sqlserver://localhost:1433;DatabaseName=peopleinfo"></property>
<!--这里我的 SqlServer的账号为sa,密码是123456 -->
<property name="username" value="sa"></property>
<property name="password" value="123456"></property>
<property name="driverClassName"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>
</bean>
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 这里的value是mapper.xml文件所在的位置 -->
<property name="mapperLocations"
value="classpath:com/ly/dao/mapper/*.xml" />
<!-- ref和前边连接数据库bean的id保持一致 -->
<property name="dataSource" ref="dataSource" />
<!-- value内是放封装对象的包名 -->
<property name="typeAliasesPackage"
value="com.ly.entity" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- value是dao层的包名 -->
<property name="basePackage" value="com.ly.dao"></property>
<!-- 与上边的bean的id保持一致 -->
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>