• mybatis,spring,springmvc框架整合实例(SSM)


            SSM 编程,即 SpringMVC + Spring + MyBatis 整合,是当前最为流行的 JavaEE 开发技术架 构。其实 SSM 整合的实质,仅仅就是将 MyBatis 整合入 Spring 。因为 SpringMVC 原本就是 Spring
    的一部分,不用专门整合。
          SSM 整合的实现方式可分为两种:基于 XML 配置方式,基于注解方式。
    3.1 搭建 SSM 开发环境
    项目结构

     

    需求:完成学生注册和信息浏览。

    1 建表 Student

    数据库名称ssm1

     

     表名student,id属性设置为自增,其他属性默认保持不变

     2 新建 Web 工程

    工程名称ssm1

    3 maven 依赖 (pom.xml文件)

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0</modelVersion>
    5. <groupId>com.it</groupId>
    6. <artifactId>ssm1</artifactId>
    7. <version>1.0-SNAPSHOT</version>
    8. <packaging>war</packaging>
    9. <properties>
    10. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    11. <maven.compiler.source>1.8</maven.compiler.source>
    12. <maven.compiler.target>1.8</maven.compiler.target>
    13. </properties>
    14. <dependencies>
    15. <dependency>
    16. <groupId>junit</groupId>
    17. <artifactId>junit</artifactId>
    18. <version>4.11</version>
    19. <scope>test</scope>
    20. </dependency>
    21. <!--servlet依赖-->
    22. <dependency>
    23. <groupId>javax.servlet</groupId>
    24. <artifactId>javax.servlet-api</artifactId>
    25. <version>3.1.0</version>
    26. <scope>provided</scope>
    27. </dependency>
    28. <!-- jsp依赖 -->
    29. <dependency>
    30. <groupId>javax.servlet.jsp</groupId>
    31. <artifactId>jsp-api</artifactId>
    32. <version>2.2.1-b03</version>
    33. <scope>provided</scope>
    34. </dependency>
    35. <!--springmvc依赖-->
    36. <dependency>
    37. <groupId>org.springframework</groupId>
    38. <artifactId>spring-webmvc</artifactId>
    39. <version>5.2.5.RELEASE</version>
    40. </dependency>
    41. <!--事务的依赖-->
    42. <dependency>
    43. <groupId>org.springframework</groupId>
    44. <artifactId>spring-tx</artifactId>
    45. <version>5.2.5.RELEASE</version>
    46. </dependency>
    47. <!--事务相关的依赖-->
    48. <dependency>
    49. <groupId>org.springframework</groupId>
    50. <artifactId>spring-jdbc</artifactId>
    51. <version>5.2.5.RELEASE</version>
    52. </dependency>
    53. <!--jackson的依赖-->
    54. <dependency>
    55. <groupId>com.fasterxml.jackson.core</groupId>
    56. <artifactId>jackson-core</artifactId>
    57. <version>2.9.0</version>
    58. </dependency>
    59. <dependency>
    60. <groupId>com.fasterxml.jackson.core</groupId>
    61. <artifactId>jackson-databind</artifactId>
    62. <version>2.9.0</version>
    63. </dependency>
    64. <!--mybatis整合依赖-->
    65. <dependency>
    66. <groupId>org.mybatis</groupId>
    67. <artifactId>mybatis-spring</artifactId>
    68. <version>1.3.1</version>
    69. </dependency>
    70. <!--mybatis依赖-->
    71. <dependency>
    72. <groupId>org.mybatis</groupId>
    73. <artifactId>mybatis</artifactId>
    74. <version>3.5.1</version>
    75. </dependency>
    76. <!--mysql驱动的依赖-->
    77. <dependency>
    78. <groupId>mysql</groupId>
    79. <artifactId>mysql-connector-java</artifactId>
    80. <version>5.1.9</version>
    81. </dependency>
    82. <!--druid数据库连接池依赖-->
    83. <dependency>
    84. <groupId>com.alibaba</groupId>
    85. <artifactId>druid</artifactId>
    86. <version>1.1.12</version>
    87. </dependency>
    88. </dependencies>
    89. <build>
    90. <resources>
    91. <resource>
    92. <directory>src/main/java</directory><!--所在的目录-->
    93. <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
    94. <include>**/*.properties</include>
    95. <include>**/*.xml</include>
    96. </includes>
    97. <filtering>false</filtering>
    98. </resource>
    99. </resources>
    100. <plugins>
    101. <plugin>
    102. <artifactId>maven-compiler-plugin</artifactId>
    103. <version>3.1</version>
    104. <configuration>
    105. <source>1.8</source>
    106. <target>1.8</target>
    107. </configuration>
    108. </plugin>
    109. </plugins>
    110. </build>
    111. </project>
    4 定义包,组织程序的结构。

    jsp 文件:

     

    5 编写配置文件

    Jdbc 属性配置文件 jdbc.properties

    1. jdbc.url=jdbc:mysql://localhost:3306/ssm1
    2. jdbc.username=root
    3. jdbc.password=123456

     Spring 配置文件 applicationContext.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    6. <!--spring配置文件:声明service,dao,工具类等对象-->
    7. <!-- 声明数据库连接属性文件的位置-->
    8. <context:property-placeholder location="classpath:conf/jdbc.properties"/>
    9. <!-- 声明数据源,连接数据库-->
    10. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
    11. init-method="init" destroy-method="close">
    12. <property name="url" value="${jdbc.url}"/>
    13. <property name="username" value="${jdbc.username}"/>
    14. <property name="password" value="${jdbc.password}"/>
    15. </bean>
    16. <!-- 声明SqlSessionFactoryBean创建SqlSessionFactory-->
    17. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    18. <property name="dataSource" ref="dataSource"/>
    19. <property name="configLocation" value="classpath:conf/mybatis.xml"/>
    20. </bean>
    21. <!-- 声明mybatis的扫描器,创建dao对象-->
    22. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    23. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    24. <property name="basePackage" value="com.it.dao"/>
    25. </bean>
    26. <!-- 声明service的注解@Service所在包名的位置-->
    27. <context:component-scan base-package="com.it.service"/>
    28. <!-- 事物的配置:注解的配置,aspectJ的配置(二选一就可以了)-->
    29. </beans>
    Springmvc 配置文件: disaptcherServlet.xml
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans.xsd
    8. http://www.springframework.org/schema/context
    9. https://www.springframework.org/schema/context/spring-context.xsd
    10. http://www.springframework.org/schema/mvc
    11. https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    12. <!--springmvc的配置文件,用来声明controller和其它web相关的对象-->
    13. <!-- 1.组件扫描器-->
    14. <context:component-scan base-package="com.it.controller"/>
    15. <!-- 2.视图解析器-->
    16. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    17. <property name="prefix" value="/WEB-INF/jsp/"/>
    18. <property name="suffix" value=".jsp"/>
    19. </bean>
    20. <!-- 3.注解驱动,注意后缀是mvc结尾的注解驱动-->
    21. <mvc:annotation-driven/>
    22. <!--该注解驱动的作用:
    23. 1.响应ajax请求,返回json
    24. 2.解决静态资源访问问题
    25. -->
    26. </beans>
    mybatis.xml
    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <!-- settings:控制mybatis全局行为-->
    7. <settings>
    8. <!-- 设置mybatis输出日志-->
    9. <setting name="logImpl" value="STDOUT_LOGGING"/>
    10. </settings>
    11. <!-- 设置别名,主要为了简化对于类名的指定-->
    12. <typeAliases>
    13. <package name="com.it.entity"/>
    14. </typeAliases>
    15. <!--sql映射文件的位置-->
    16. <mappers>
    17. <!-- name:是包名,这个包中的所有mapper.xml一次都能够加载
    18. 使用package的要求:
    19. 1.mapper文件名和dao接口名必须完全一样,包括大小写
    20. 2.mapping文件和dao接口必须在同一目录
    21. -->
    22. <package name="com.it.dao"/>
    23. </mappers>
    24. </configuration>
    6 定义 web.xml
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    5. version="4.0">
    6. <!-- 注册中央调度器-->
    7. <servlet>
    8. <servlet-name>springmvc</servlet-name>
    9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    10. <init-param>
    11. <param-name>contextConfigLocation</param-name>
    12. <param-value>classpath:conf/dispatcherServlet.xml</param-value>
    13. </init-param>
    14. <load-on-startup>1</load-on-startup>
    15. </servlet>
    16. <servlet-mapping>
    17. <servlet-name>springmvc</servlet-name>
    18. <url-pattern>*.do</url-pattern>
    19. </servlet-mapping>
    20. <!-- 注册spring的监听器-->
    21. <listener>
    22. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    23. </listener>
    24. <context-param>
    25. <param-name>contextConfigLocation</param-name>
    26. <param-value>classpath:conf/applicationContext.xml</param-value>
    27. </context-param>
    28. <!-- 注册字符集过滤器-->
    29. <filter>
    30. <filter-name>characterEncodingFilter</filter-name>
    31. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    32. <init-param>
    33. <param-name>encoding</param-name>
    34. <param-value>utf-8</param-value>
    35. </init-param>
    36. <init-param>
    37. <param-name>forceRequestEncoding</param-name>
    38. <param-value>true</param-value>
    39. </init-param>
    40. <init-param>
    41. <param-name>forceResponseEncoding</param-name>
    42. <param-value>true</param-value>
    43. </init-param>
    44. </filter>
    45. <filter-mapping>
    46. <filter-name>characterEncodingFilter</filter-name>
    47. <url-pattern>/*</url-pattern>
    48. </filter-mapping>
    49. </web-app>
    7 实体类 Student
    1. package com.it.entity;
    2. public class Student {
    3. private Integer id;
    4. private String name;
    5. private Integer age;
    6. public Integer getId() {
    7. return id;
    8. }
    9. public void setId(Integer id) {
    10. this.id = id;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public Integer getAge() {
    19. return age;
    20. }
    21. public void setAge(Integer age) {
    22. this.age = age;
    23. }
    24. @Override
    25. public String toString() {
    26. return "Student{" +
    27. "id=" + id +
    28. ", name='" + name + '\'' +
    29. ", age=" + age +
    30. '}';
    31. }
    32. }
    8 Dao 接口和 sql 映射文件
    dao接口StudentDAO
    1. package com.it.dao;
    2. import com.it.entity.Student;
    3. import java.util.List;
    4. public interface StudentDao {
    5. int insertStudent(Student student);
    6. List<Student> selectStudents();
    7. }
    sql映射文件StudentDao.xml
    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.it.dao.StudentDao">
    6. <select id="selectStudents" resultType="com.it.entity.Student">
    7. select id,name,age from student order by id desc
    8. </select>
    9. <insert id="insertStudent">
    10. insert into student(name,age) values(#{name},#{age})
    11. </insert>
    12. </mapper>
    9 Service 接口和实现类
    service接口StudentService
    1. package com.it.service;
    2. import com.it.entity.Student;
    3. import java.util.List;
    4. public interface StudentService {
    5. int addStudent(Student student);
    6. List<Student> queryStudents();
    7. }

    实现类StudentServiceImpl

    1. package com.it.service.impl;
    2. import com.it.dao.StudentDao;
    3. import com.it.entity.Student;
    4. import com.it.service.StudentService;
    5. import org.springframework.stereotype.Service;
    6. import javax.annotation.Resource;
    7. import java.util.List;
    8. @Service
    9. public class StudentServiceImpl implements StudentService {
    10. //引用类型的自动注入,@Autowired,@Resource
    11. @Resource
    12. private StudentDao studentDao;
    13. @Override
    14. public int addStudent(Student student) {
    15. int i = studentDao.insertStudent(student);
    16. return i;
    17. }
    18. @Override
    19. public List<Student> queryStudents() {
    20. List<Student> students = studentDao.selectStudents();
    21. return students;
    22. }
    23. }
    10 处理器定义
    1. package com.it.controller;
    2. import com.it.entity.Student;
    3. import com.it.service.StudentService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.stereotype.Controller;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import org.springframework.web.bind.annotation.ResponseBody;
    8. import org.springframework.web.servlet.ModelAndView;
    9. import java.util.List;
    10. @Controller
    11. @RequestMapping(value = "/student")
    12. public class StudentController {
    13. @Autowired
    14. private StudentService service;
    15. //注册学生
    16. @RequestMapping(value = "/addStudent.do")
    17. public ModelAndView addStudent(Student student){
    18. ModelAndView mv=new ModelAndView();
    19. String tips="注册失败";
    20. //调用service处理student
    21. int i = service.addStudent(student);
    22. if (i>0){
    23. //注册成功
    24. tips="学生【"+student.getName()+"】注册成功!";
    25. }
    26. //添加数据
    27. mv.addObject("tips",tips);
    28. //指定结果页面
    29. mv.setViewName("result");
    30. return mv;
    31. }
    32. //处理学生的查询,响应ajax
    33. @RequestMapping(value = "/queryStudent.do")
    34. @ResponseBody
    35. public List<Student> queryStudent(){
    36. //参数检查,简单的数据处理
    37. List<Student> students = service.queryStudents();
    38. return students;
    39. }
    40. }
    11 定义视图 - 首页文件 --- index.jsp
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <%
    3. String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()
    4. +request.getServerName()+"/";
    5. %>
    6. <html>
    7. <head>
    8. <title>用户操作的功能入口</title>
    9. <base href="<%=basePath%>"/>
    10. </head>
    11. <body>
    12. <div align="center">
    13. <p>SSM整合的例子</p>
    14. <img src="images/pic1.jpg" width="1000px" height="500px">
    15. <table>
    16. <tr>
    17. <td><a href="addStudent.jsp">注册学生</a></td>
    18. </tr>
    19. <tr>
    20. <td><a href="listStudent.jsp">浏览学生</a></td>
    21. </tr>
    22. </table>
    23. </div>
    24. </body>
    25. </html>
    12 注册学生页面 --- addStudent.jsp
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <%
    3. String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()
    4. +request.getServerName()+"/";
    5. %>
    6. <html>
    7. <head>
    8. <title>注册学生</title>
    9. <base href="<%=basePath%>"/>
    10. </head>
    11. <body>
    12. <div align="center">
    13. <form action="student/addStudent.do" method="post">
    14. <table>
    15. <tr>
    16. <td>姓名:</td>
    17. <td><input type="text" name="name"></td>
    18. </tr>
    19. <tr>
    20. <td>年龄:</td>
    21. <td><input type="text" name="age"></td>
    22. </tr>
    23. <tr>
    24. <td>
    25. <input type="submit" value="注册">
    26. </td>
    27. </tr>
    28. </table>
    29. </form>
    30. </div>
    31. </body>
    32. </html>
    13 浏览学生页面 --- listStudent.jsp
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <%
    3. String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()
    4. +request.getServerName()+"/";
    5. %>
    6. <html>
    7. <head>
    8. <title>查询学生ajax</title>
    9. <base href="<%=basePath%>"/>
    10. <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    11. <script type="text/javascript">
    12. $(function () {
    13. //在当前页面dom对象加载后,执行loadStudentData()
    14. loadStudentData();
    15. $("#btnLoader").click(function () {
    16. loadStudentData();
    17. })
    18. function loadStudentData() {
    19. $.ajax({
    20. url:"student/queryStudent.do",
    21. type:"post",
    22. dataType:"json",
    23. success:function (data) {
    24. //清除旧的数据
    25. $("#info").html("");
    26. //增加新的数据
    27. $.each(data,function (i,n) {
    28. $("#info").append("<tr>")
    29. .append("<td>"+n.id+"</td>")
    30. .append("<td>"+n.name+"</td>")
    31. .append("<td>"+n.age+"</td>")
    32. .append("</tr>")
    33. })
    34. }
    35. })
    36. }
    37. })
    38. </script>
    39. </head>
    40. <body>
    41. <div align="center">
    42. <table>
    43. <thead>
    44. <tr>
    45. <td>学号</td>
    46. <td>姓名</td>
    47. <td>年龄</td>
    48. </tr>
    49. </thead>
    50. <tbody id="info">
    51. </tbody>
    52. <input type="button" id="btnLoader"value="查询数据">
    53. </table>
    54. </div>
    55. </body>
    56. </html>
    14 注册结果页面 --- result.jsp
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>Title</title>
    5. </head>
    6. <body>
    7. result.jsp页面,注册结果是:${tips}
    8. </body>
    9. </html>

    项目结果

    运行项目后自动进入首界面

     1.点击注册学生链接

    这是数据库中原本存在的数据

     

    点击 注册

    查看数据库是否成功添加

    可以看到已经成功添加

    2.返回首页,点击浏览学生链接

  • 相关阅读:
    计算机网络(自顶向下方法)-应用层
    Java基于springboot+vue的共享电动车管理系统 nodejs
    【20221105】【每日一题】删除二叉搜索树中的节点
    【JavaScript】-- 继承
    npm发布vue3自定义组件库--方法一
    抗击疫情静态HTML网页作业作品 大学生抗疫感动专题页设计制作成品 简单DIV CSS布局网站
    记录C++类中的一次函数调用
    Vue学习笔记(六)回顾Object.defineproperty方法
    无胁科技-TVD每日漏洞情报-2022-11-15
    SpringBoot读取json文件
  • 原文地址:https://blog.csdn.net/weixin_59334478/article/details/125414719