加入依赖

  • 三个框架所需要的依赖

    1. <dependencies>
    2. <!-- 依赖spring-webmvc -->
    3. <dependency>
    4. <groupId>org.springframework</groupId>
    5. <artifactId>spring-webmvc</artifactId>
    6. <version>5.2.9.RELEASE</version>
    7. </dependency>
    8. <!-- JSP-API的依赖 -->
    9. <dependency>
    10. <groupId>javax.servlet.jsp</groupId>
    11. <artifactId>jsp-api</artifactId>
    12. <version>2.2</version>
    13. <scope>provided</scope><!-- ??? -->
    14. </dependency>
    15. <!-- servlet-api依赖 -->
    16. <dependency>
    17. <groupId>javax.servlet</groupId>
    18. <artifactId>javax.servlet-api</artifactId>
    19. <version>3.1.0</version>
    20. <scope>provided</scope>
    21. </dependency>
    22. <!-- jstl标签库依赖 -->
    23. <dependency>
    24. <groupId>javax.servlet</groupId>
    25. <artifactId>jstl</artifactId>
    26. <version>1.2</version>
    27. </dependency>
    28. <!-- json处理 -->
    29. <dependency>
    30. <groupId>com.fasterxml.jackson.core</groupId>
    31. <artifactId>jackson-annotations</artifactId>
    32. <version>2.9.0</version>
    33. </dependency>
    34. <dependency>
    35. <groupId>com.fasterxml.jackson.core</groupId>
    36. <artifactId>jackson-databind</artifactId>
    37. <version>2.9.0</version>
    38. </dependency>
    39. <dependency>
    40. <groupId>com.fasterxml.jackson.core</groupId>
    41. <artifactId>jackson-core</artifactId>
    42. <version>2.9.0</version>
    43. </dependency>
    44. <!-- Spring核心容器包含的模块 -->
    45. <dependency>
    46. <groupId>org.springframework</groupId>
    47. <artifactId>spring-context-support</artifactId>
    48. <version>5.2.9.RELEASE</version>
    49. </dependency>
    50. <!-- MyBatis的依赖 -->
    51. <dependency>
    52. <groupId>org.mybatis</groupId>
    53. <artifactId>mybatis</artifactId>
    54. <version>3.4.6</version>
    55. </dependency>
    56. <!-- spring整合MyBatis的中间包 -->
    57. <dependency>
    58. <groupId>org.mybatis</groupId>
    59. <artifactId>mybatis-spring</artifactId>
    60. <version>1.3.2</version>
    61. </dependency>
    62. <!-- mysql驱动 -->
    63. <dependency>
    64. <groupId>mysql</groupId>
    65. <artifactId>mysql-connector-java</artifactId>
    66. <version>5.1.47</version>
    67. </dependency>
    68. <!-- springjdbc中间包 -->
    69. <dependency>
    70. <groupId>org.springframework</groupId>
    71. <artifactId>spring-jdbc</artifactId>
    72. <version>5.2.9.RELEASE</version>
    73. </dependency>
    74. <!-- 德鲁伊连接池 -->
    75. <dependency>
    76. <groupId>com.alibaba</groupId>
    77. <artifactId>druid</artifactId>
    78. <version>1.1.10</version>
    79. </dependency>
    80. <!-- webjars的形式依赖jquery -->
    81. <dependency>
    82. <groupId>org.webjars</groupId>
    83. <artifactId>jquery</artifactId>
    84. <version>3.6.0</version>
    85. </dependency>
    86. <!-- 文件上传组件 -->
    87. <dependency>
    88. <groupId>commons-fileupload</groupId>
    89. <artifactId>commons-fileupload</artifactId>
    90. <version>1.4</version>
    91. </dependency>
    92. <dependency>
    93. <groupId>org.webjars</groupId>
    94. <artifactId>jquery</artifactId>
    95. <version>3.6.0</version>
    96. </dependency>
    97. </dependencies>

    相关插件:

    <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <!-- 如果不配置,默认情况下,不会将java目录下的资源文件打包 -->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
    
    <plugins>
      <!-- maven内置 的tomcat7插件 -->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <!-- 可以灵活配置工程路径 -->
          <path>/</path>
          <!-- 可以灵活配置端口号 -->
          <port>8080</port>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    </build>
    

    相关配置文件

  • applicationContext.xml——Spring的核心配置文件

  • mybatis-config.xml——MyBatis的核心配置文件
  • spring-mvc.xml——SpringMVC的配置文件(其实SpringMVC的配置文件和Spring配置文件是同一种)
  • db.properties——相关参数
  • web.xml——tomcat配置文件

applicationContext.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 引入外部资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置扫描包 -->
    <context:component-scan base-package="com.quail.service"/>

    <!-- 配置数据源 -->
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"/>
        <!--        <property name="driverClassName" value="${driver}"/>-->
        <!--        <property name="username" value="${username}"/>-->
        <!--        <property name="password" value="${password}"/>-->
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 可以继续配置其他属性 -->
    </bean>

    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="datasource"/>
        <!-- 别名包 -->
        <property name="typeAliasesPackage" value="com.quail.pojo"/>
        <!-- mapper文件的位置 -->
        <!--        <property name="mapperLocations" value="classpath:com/st/mapper"/>-->
        <!-- MyBatis配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <!-- 配置一个mapper的扫描bean -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置mapper所在包 -->
        <property name="basePackage" value="com.quail.mapper"/>
    </bean>
</beans>

spring-mvc.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 扫描包 -->
    <context:component-scan base-package="com.quail.controller" />

    <!-- 开启MVC注解驱动 -->
    <mvc:annotation-driven />

    <!-- 静态资源不过滤 -->
    <mvc:default-servlet-handler/>

    <!-- 视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 配置文件上传的相关配置 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="1024400"/>
    </bean>
</beans>

mybatis-config.xml:在Spring的核心配置文件中可以配置数据库连接,所以该配置文件不需要配置了

<?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>

<!--    <properties resource="db.properties">-->
<!--        &lt;!&ndash; 还可以额外自定义属性 &ndash;&gt;-->
<!--        <property name="username" value="admin"/>-->
<!--        <property name="size" value="18"/>-->
<!--    </properties>-->

<!--    <settings>-->
<!--        <setting name="logImpl" value="STDOUT_LOGGING"/>-->
<!--        &lt;!&ndash; 延迟加载 &ndash;&gt;-->
<!--&lt;!&ndash;        <setting name="lazyLoadingEnabled" value="true"/>&ndash;&gt;-->
<!--&lt;!&ndash;        <setting name="aggressiveLazyLoading" value="false"/>&ndash;&gt;-->
<!--    </settings>-->

<!--    <typeAliases>-->
<!--        &lt;!&ndash; 配置一个别名 &ndash;&gt;-->
<!--        <typeAlias alias="teacher" type="com.quail.pojo.Teacher"/>-->
<!--        &lt;!&ndash; 配置一个包,这个包下的所有的类都可以直接使用类的简称(不区分首字母大小写) &ndash;&gt;-->
<!--        <package name="com.quail.pojo" />-->
<!--    </typeAliases>-->

<!--    &lt;!&ndash;-->
<!--        环境配置:数据库的连接信息-->
<!--        default:必须和某个environment的id值一样。-->
<!--        告诉mybatis使用哪个数据库的连接信息。就是访问哪个数据库-->
<!--    &ndash;&gt;-->
<!--    <environments default="mybatis">-->
<!--        &lt;!&ndash;-->
<!--            environment:一个数据库信息的配置,环境-->
<!--            id:唯一值,自定义,表示环境名称-->
<!--        &ndash;&gt;-->
<!--        <environment id="mybatis">-->
<!--            &lt;!&ndash;-->
<!--                transactionManager:mybatis的事务类型-->
<!--                type:JDBC(表示使用jdbc中的Connection对象的commit,rollback做事务处理)-->
<!--            &ndash;&gt;-->
<!--            <transactionManager type="JDBC"></transactionManager>-->
<!--            &lt;!&ndash;-->
<!--                dataSource:表示数据源,连接数据库-->
<!--                type:表示数据源的类型,POOLED表示使用连接池-->
<!--            &ndash;&gt;-->
<!--            <dataSource type="POOLED">-->
<!--                <property name="driver" value="${driver}"/>-->
<!--                <property name="url" value="${url}"/>-->
<!--                <property name="username" value="${username}"/>-->
<!--                <property name="password" value="${password}"/>-->
<!--            </dataSource>-->
<!--        </environment>-->
<!--    </environments>-->

<!--    &lt;!&ndash;sql mapper(sql映射文件)的位置&ndash;&gt;-->
<!--    <mappers>-->
<!--        <mapper resource="com/quail/dao/TeacherMapper.xml"/>-->
<!--        <mapper resource="com/quail/dao/StudentMapper.xml"/>-->
<!--    </mappers>-->
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 这个监听器会根据applicationContext.xml文件创建一个spring容器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 全局参数,用来配置spring配置文件的位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- 前端控制器(核心控制器) -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

项目结构

image.png
mapper代替之前的dao的功能,用于实现数据的持久化操作
通过注解、接口和mapper.xml文件配合使用。

public interface StudentMapper {

    List<Student> queryAll();
}
<?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.quail.mapper.StudentMapper">
    <resultMap type="com.quail.pojo.Student" id="StudentMap">
        <result property="stuId" column="stuId"/>
        <result property="stuName" column="stuName"/>
        <result property="loginPass" column="loginPass"/>
        <result property="stuGender" column="stuGender"/>
        <result property="stuAge" column="stuAge"/>
        <result property="stuBirth" column="stuBirth"/>
        <result property="stuTel" column="stuTel"/>
        <result property="stuEducation" column="stuEducation"/>
        <result property="status" column="status"/>
        <result property="classId" column="classId"/>
    </resultMap>
    <select id="queryAll" resultMap="StudentMap">
        select * from student
    </select>
</mapper>
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public List<Student> queryAll() {
        return studentMapper.queryAll();
    }
}

通过@Autowired注解,注入接口的实现。

后端控制器

@Controller
//@RequestMapping("/stu")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/queryAll")
    @ResponseBody
    public ModelAndView queryAll(){
        ModelAndView model = new ModelAndView();
        List<Student> students = studentService.queryAll();
        model.addObject("students",students);
        model.setViewName("student-list");
        return model;
    }
}

执行流程

image.png

需要注意的问题

  • 前端控制器中的<``**url-pattern**``>填写路径需要注意:如果是请求项目中的静态文件,这里的路径不能是“/”,可以是“/”、“.do”、“.action”,加后缀的方式。原因是静态文件会被过滤,我们需要在spring-mvc.xml中配置<mvc:default-servlet-handler/>让SpringMVC不过滤,而带“”的url会被浏览器默认为是text格式显示。
  • 注意各jar包的版本,可以适当用新版本。
  • ModelAndView对象的使用:
    • 当model.addObject(map)时,没有传入key,获取值可以直接通过map的key获取
    • 当model.addObject(list)时,没有传入key,获取值通过list中的类型的首字母小写+List获取默认的key
      • 例:List —> key:studentList