第一次整合SSM实例

SSM整合

1.1SSM整合思路

SSM思路:SpringMVC+Spring+MyBatis(IBatis),所以有人叫做SSI整合,SSM整合是使用三个框架的优势功能,三个框架对应三层架构的三层,SpringMVC是视图层,Spring是业务层,MyBatis是持久层

SSM整合,需要把对象交给容器管理,让容器去创建项目中要使用的java对象,现在有两个容器

第一个是Spring容器:Spring容器是管理service和dao等对象的,是业务层对象的容器

第二个是SpringMVC容器:管理控制器对象的,是视图层对象。

SSM整合就是把对象交给容器管理,两个容器共存,各自负责管理不同的对象,把对象声明到配置文件中,让两个容器创建对象,Spring创建service,dao,SpringMVC创建controller。

3.2容器的创建

Spring容器创建:在web.xml声明了监听器ContextLoaderListener,这个功能框架写好了,功能是创建spring的容器对象WebApplicationContext,在创建WebApplicationContext对象时,读取spring的配置文件,读取文件的时候,遇到bean标签或者注解,就能创建service,dao等对象,放到容器中。

SpringMVC容器:在web.xml声明了中央调度器DispatcherServlet,在这个servlet的init()方法中,创建了容器对象WebApplicationContext,在创建WebApplicationContext对象,读取springmvc的配置文件,读取文件的时候,遇到@Controller注解,创建控制器controller对象,放到容器中。

内存中,创建对象

WebApplicationContext spring=new WebApplicationContext();//spring-map(service,dao)

WebApplicationContext springmvc=new WebApplicationContext();//springmvc-map(controller)

SpringMVC容器和Spring容器的关系:设计上SpringMVC容器对象是Spring容器的子容器。Spring是父容器,SpringMVC是子容器,相当于Java中的继承关系。

3.3SSM整合开发步骤

1.使用student2表,里面有id,name,age属性

2.创建maven web项目

3.修改pom.xml加入依赖:spring,springmvc,mybatis,mybatis-spring,mysql驱动,druid,jackson

 <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>javax.servlet-api</artifactId>
       <version>4.0.1</version>
   </dependency>

   <dependency>
       <groupId>javax.servlet.jsp</groupId>
       <artifactId>jsp-api</artifactId>
       <version>2.2</version>
   </dependency>

   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-tx</artifactId>
       <version>5.3.12</version>
   </dependency>
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-jdbc</artifactId>
       <version>5.3.12</version>
   </dependency>

   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-webmvc</artifactId>
       <version>5.3.12</version>
   </dependency>

   <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>8.0.26</version>
   </dependency>
   <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid</artifactId>
       <version>1.2.8</version>
   </dependency>
   <dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-core</artifactId>
       <version>2.13.0</version>
   </dependency>
   <dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-databind</artifactId>
       <version>2.13.0</version>
   </dependency>

   <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis-spring</artifactId>
       <version>1.3.1</version>
   </dependency>
   <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis</artifactId>
       <version>3.5.7</version>
   </dependency>

添加插件:

<resources>
   <resource>
       <directory>src/main/java</directory><!--所在的目录-->
       <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
           <include>**/*.properties</include>
           <include>**/*.xml</include>
       </includes>
       <filtering>false</filtering>
   </resource>
   <resource>
               <directory>src/main/resources</directory><!--所在的目录-->
               <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
                   <include>**/*.properties</include>
                   <include>**/*.xml</include>
               </includes>
               <filtering>false</filtering>
           </resource>
</resources>

4.写web.xml:声明容器对象

1)声明spring的监听器ContextLoaderListener:创建spring的容器对象,创建service,dao对象

<!--声明spring监听器-->
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:conf/applicationContext.xml</param-value>
    <!--需要在resources下创建一个conf文件夹,然后创建spring的配置文件,文件名为applicationContext-->
</context-param>
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2)声明springmvc的中央调度器DispatcherServlet:创建springmvc容器对象,创建controller对象

<!--声明springmvc中央调度器-->
<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:conf/springmvc.xml</param-value>
       <!--需要在resources下创建一个conf文件夹,然后创建springmvc的配置文件,文件名为springmvc-->
   </init-param>
   <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
   <servlet-name>dispatcherServlet</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

3)声明字符集的过滤器CharacterEncodingFilter,解决post请求乱码的问题

<!--声明字符集过滤器-->
<filter>
   <filter-name>characterEncodingFilter</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>
   <init-param>
       <param-name>forceRequestEncoding</param-name>
       <param-value>true</param-value>
   </init-param>
   <init-param>
       <param-name>forceResponseEncoding</param-name>
       <param-value>true</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>characterEncodingFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

5.创建程序中的包,dao,service,controller,entity

dao包:StudentDao

package com.hao.dao;

import com.hao.entity.Student;

import java.util.List;

public interface StudentDao {
   int insertStudent(Student student);
   List<Student> selectStudents();
}

dao包StudentDao.xml

<?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.hao.dao.StudentDao">

   <insert id="insertStudent">
      insert into student2(name,age) values(#{name},#{age})
   </insert>

   <select id="selectStudents" resultType="com.hao.entity.Student">
      select id,name,age from student2 order by id asc
   </select>

</mapper>

controller包StudentController

package com.hao.controller;

import com.hao.entity.Student;
import com.hao.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
   @Autowired
   private StudentService studentService;

   @RequestMapping("/addStudent.do")
   public ModelAndView addStudent(Student student) {
       ModelAndView mv = new ModelAndView();
       int rows = studentService.addStudent(student);

       String msg="注册失败!!!!";
       if(rows>0){
           //表示添加成功,给用户返回数据和视图
           msg="注册成功";
      }

       mv.addObject("msg","用户:"+student.getName()+","+msg);
       mv.setViewName("result");
       return mv;
  }

   @RequestMapping("/queryStudent.do")
   @ResponseBody
   public List<Student> queryStudents(){
       List<Student> students=studentService.queryStudents();
       return students;
  }
}

entity包Student

package com.hao.entity;

public class Student {
   private Integer id;
   private String name;
   private Integer age;

   public Integer getId() {
       return id;
  }

   public void setId(Integer id) {
       this.id = id;
  }

   public String getName() {
       return name;
  }

   public void setName(String name) {
       this.name = name;
  }

   public Integer getAge() {
       return age;
  }

   public void setAge(Integer age) {
       this.age = age;
  }

   @Override
   public String toString() {
       return "Student{" +
               "id=" + id +
               ", name='" + name + '\'' +
               ", age=" + age +
               '}';
  }
}

service包StudentService

package com.hao.service;

import com.hao.entity.Student;

import java.util.List;

public interface StudentService {
   int addStudent(Student student);
   List<Student> queryStudents();
}

service的子包impl包中StudentServiceImpl

package com.hao.service.impl;

import com.hao.dao.StudentDao;
import com.hao.entity.Student;
import com.hao.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
   @Autowired
   private StudentDao dao;
   @Override
   public int addStudent(Student student) {
       int rows=dao.insertStudent(student);
       return rows;
  }

   @Override
   public List<Student> queryStudents() {
       List<Student> list=dao.selectStudents();
       return list;
  }
}

6.写spring,springmvc,mybatis配置文件

spring配置文件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:context="http://www.springframework.org/schema/context"
      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">

   <!--spring配置文件:声明service,dao,工具类,事务配置-->

   <context:component-scan base-package="com.hao.service"/>
   <context:property-placeholder location="classpath:conf/jdbc.properties"/>

   <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
           init-method="init" destroy-method="close">

       <property name="url" value="${jdbc.url}"/>
       <property name="username" value="${jdbc.username}"/>
       <property name="password" value="${jdbc.password}"/>

   </bean>
   <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
       <property name="configLocation" value="classpath:conf/mybatis.xml"/>
   </bean>
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="sqlSessionFactoryBeanName" value="factory"/>
       <property name="basePackage" value="com.hao.dao"/>
   </bean>
   <!--事务配置-->

</beans>

springmvc配置文件springmvc.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:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      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
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

   <!--springmvc配置文件,声明controller,视图解析器等web开发中的对象-->
   <!--注解扫描器-->
   <context:component-scan base-package="com.hao.controller"/>
   <!--注册视图视图解析器-->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/jsp/"/>
       <property name="suffix" value=".jsp"/>
   </bean>
   <!--声明注解驱动-->
   <!--
       作用:
       1.创建HttpMessageConverter接口的7个实现类对象,处理java对象到json的转换
       2.解决静态资源中,动态资源访问失败的问题
   -->
   <mvc:annotation-driven/>

</beans>

mybatis配置文件mybatis.xml

<?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>
   <!--
   <settings>
       <setting name="logImpl" value="STDOUT_LOGGING" />
   </settings>
   -->

   <typeAliases>
       <!--entity包中的类名就是别名-->
       <package name="com.hao.entity"/>
   </typeAliases>
   <mappers>
       <!--加载dao包中的所有mapper文件-->
       <package name="com.hao.dao"/>
   </mappers>
</configuration>

最后加上一个properties文件,用来设置自己的数据库信息,其中里面的属性名分别为:jdbc.url,jdbc.username,jdbc.password

7,写java代码,实体类,dao接口和mapper文件,service类,controller类,使用注解声明对象和赋值

8.创建视图文件,各种jsp

result.jsp(此文件在WEB-INF文件夹下新建的jsp文件夹中,用于保护数据)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
<h3>result.jsp/</h3><br>
${msg}<br>


</body>
</html>

addStudent.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>注册学生</title>
</head>
<body>
<div align="center">
   <form action="student/addStudent.do" method="post">
       <table>
           <tr>
               <td>姓名:</td>
               <td><input type="text" name="name"></td>
           </tr>
           <tr>
               <td>年龄:</td>
               <td><input type="text" name="age"></td>
           </tr>
           <tr>
               <td>操作</td>
               <td><input type="submit" value="注册"></td>
           </tr>
       </table>
   </form>
</div>
</body>
</html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
<div align="center">
   <p>SSM整合实例</p>
   <table>
       <tr>
           <td><a href="addStudent.jsp">添加学生</a> </td>
       </tr>
       <tr>
           <td><a href="listStudent.jsp">浏览学生</a> </td>
       </tr>
   </table>
</div>
</body>
</html>

listStudent.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>浏览学生</title>
   <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
   <script type="text/javascript">
       getStudentInfo();
       $(function (){
           $("#doAjax").click(function (){
               getStudentInfo();
          })
      })
       function getStudentInfo(){
           $.ajax({
               url:"student/queryStudent.do",
               dataType:"json",
               success:function (resp){
                   $("#stuinfo").empty();
                   $.each(resp,function (i,n){
                       $("#stuinfo").append("<tr><td>"+n.id+"</td><td>"+n.name+"</td><td>"+n.age+"</td></tr>")
                  })
              }
          })
      }
   </script>
</head>
<body>
<div align="center">
   <p>浏览学生&nbsp;&nbsp;<button id="doAjax">点击获取学生信息</button></p>
   <table>
       <thead>
           <tr>
               <td>学号</td>
               <td>姓名</td>
               <td>年龄</td>
           </tr>
       </thead>
       <tbody id="stuinfo">

       </tbody>
   </table>
</div>

</body>
</html>

目录级别如图所示:

 

posted @ 2021-11-18 20:40  AMHAO  阅读(76)  评论(0编辑  收藏  举报