SpringMVC学习笔记7——SSM整合1

整合思路

本次学习笔记进行SSM(即 SpringMVC + Spring + MyBatis 整合)的整合,先理清每个框架的任务

  • SpringMVC:视图层,界面层,负责接收请求,显示处理结果
  • Spring:业务层,管理Service,dao,工具类对象
  • MyBatis:持久层,负责访问数据库

简要过程:用户发起请求==> SpringMVC接收 ==>Spring的Service对象 ==> MyBatis处理数据
在SSM整合中存在两个容器:

  • SpringMVC容器:管理Controller控制器对象
  • Spring容器:管理Service,dao,工具类对象

我们要坐的就是把要使用的对象交给合适的容器来创建和管理;如把Controller和Web开发相关的对象交给springmvc容器,这些对象卸载springmvc的配置文件中;把service和dao对象定义在spring的配置文件中,让spring管理这些对象
需要注意的是,springmvc容器和spring容器是有确定关系的,springmvc容器时spring容器的子容器,类似java中的继承,所以崽可以访问爹的内容,即在子容器中的Controller可以访问父容器中的Service对象,就可以实现Controller使用service对象了

实现步骤

  1. 创建对应的数据库表(id auto_increment, name, age)
  2. 新建maven web项目
    用预设的web骨架
    maven路径记得换成自己的
    先看以下项目的结构
    项目结构
  3. 加入依赖
    springmvc,spring,mybatis三个框架依赖,jackson,mysql,druid连接池,jsp和servlet依赖
<properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   <maven.compiler.source>1.8</maven.compiler.source>
   <maven.compiler.target>1.8</maven.compiler.target>
 </properties>

 <dependencies>
   <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.11</version>
     <scope>test</scope>
   </dependency>

   <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
     <scope>provided</scope>
   </dependency>
   <!-- jsp依赖 -->
   <dependency>
     <groupId>javax.servlet.jsp</groupId>
     <artifactId>jsp-api</artifactId>
     <version>2.2.1-b03</version>
     <scope>provided</scope>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>5.2.5.RELEASE</version>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-tx</artifactId>
     <version>5.2.5.RELEASE</version>
   </dependency>

   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-jdbc</artifactId>
     <version>5.2.5.RELEASE</version>
   </dependency>
   <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-core</artifactId>
     <version>2.9.0</version>
   </dependency>
   <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.9.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.1</version>
   </dependency>
   <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>5.1.9</version>
   </dependency>
   <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
     <version>1.1.12</version>
   </dependency>

 </dependencies>
 <build>
 <resources>
   <resource>
     <directory>src/main/java</directory><!--所在的目录-->
     <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
       <include>**/*.properties</include>
       <include>**/*.xml</include>
     </includes>
     <filtering>false</filtering>
   </resource>
 </resources>
 <plugins>
   <plugin>
     <artifactId>maven-compiler-plugin</artifactId>
     <version>3.1</version>
     <configuration>
       <source>1.8</source>
       <target>1.8</target>
     </configuration>
   </plugin>
 </plugins>
</build>	
  1. 写web.xml

    1. 注册DispatcherServlet:
      目的:
      1. 创建springmvc容器对象才能创建Controller类对象
      2. 创建的时Servlet才能接收用户请求
    <servlet>
    <servlet-name>myspringmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
      <!--springmvc配置文件位置的属性-->
      <param-name>contextConfigLocation</param-name>
      <!--指定自定义文件位置-->
      <param-value>classpath:conf/dispatcherServlet.xml</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    	<servlet-name>myspringmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
    1. 注册spring的监听器ContextLoaderListener:
      目的:创建spring容器对象才能创建service,dao对象
    	<context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath:conf/applicationContext.xml</param-value>
     </context-param>
    <!--注册spring的监听器-->
    <listener>
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    1. 注册字符集过滤器:解决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>
    
  2. 创建包
    Controller包,service包,dao包和实体类包名创建好

  3. 写springmvc,spring和mybatis的配置文件

    springmvc配置文件
    	<!--springmvc配置文件-->
    	<context:component-scan base-package="com.ssm.controller"/>
    	
    	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    	</bean>
    	
    	<mvc:annotation-driven/>
    	<!--
        	1.响应ajax请求,返回json
        	2.解决静态资源访问问题
    	-->
    
    spring配置文件
    <!--spring配置文件:声明service,dao和工具类等对象-->
    
    <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>
    
    <!--SqlSessionFactoryBean创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:conf/mybatis.xml"/>
    </bean>
    
    <!--声明mybatis扫描器,创建dao对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <property name="basePackage" value="com.ssm.dao" />
    </bean>
    
    <!--声明Service的注解@Service所在的包名位置-->
    <context:component-scan base-package="com.ssm.service"/>
    
    <!--事务配置:注解的配置,aspectj的配置-->
    
    mybatis主配置文件
    <!--设置别名-->
    <typeAliases>
        <!--实体类所在的包名-->
        <package name="com.ssm.domain"/>
    </typeAliases>
    
    
    <mappers>
        <!--该目录下所有mapper文件一次性加载-->
        <package name="com.ssm.dao"/>
    </mappers>
    
    数据库的属性配置文件
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&amp;characterEncoding=UTF-8
    jdbc.username=root
    jdbc.password=root
    
  4. 写代码

    dao接口
    public interface StudentDao {
    
    int insertStudent(Student student);
    List<Student> selectStudents();
    }
    
    mapper文件
    <mapper namespace="com.ssm.dao.StudentDao">
    
    
    <select id="selectStudents" resultType="Student">
        select id,name,age from student group by id desc 
    </select>
    
    <insert id="insertStudent">
        insert into student(name,age) values(#{name},#{age})
    </insert>
    
    </mapper>
    
    service
    public interface StudentService {
    
    int addStudent(Student student);
    List<Student> findStudent();
    }
    
    实现类
    @Service
    public class StudentServiceImpl implements StudentService {
    
    
    @Resource
    private StudentDao studentDao;
    @Override
    public int addStudent(Student student) {
    
        int num=studentDao.insertStudent(student);
        return num;
    }
    
    @Override
    public List<Student> findStudent() {
        return studentDao.selectStudents();
    }
    }
    
    controller
    @Controller
    public class StudentController {
    
    @Resource
    private StudentService studentService;
    
    @RequestMapping("student//addStudent.do")
    public ModelAndView addStudent(Student student){//注册学生
    
        ModelAndView mv=new ModelAndView();
    
        String tips="注册失败";
    
        //调用service处理student
        int num=studentService.addStudent(student);
        if(num > 0){
            //注册成功
            tips="学生【"+student.getName()+"】注册成功";
        }
    
        //添加数据
        mv.addObject("tips",tips);
    
        //指定结果页面
        mv.setViewName("result");
    
        return mv;
    
    	}
    }
    
    实体类(略)
  5. 写jsp页面

    index.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%
    String basePath = request.getScheme() + "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
    %>
    <html>
    <head>
    <title>首页</title>
    <base href="<%=basePath%>"/>
    </head>
    <body>
        <div align="center">
            <p>SSM整合注册页面</p>
            <img src="images/p2.jpg">
            <table>
                <tr>
                    <td><a href="addStudent.jsp">注册学生</a></td>
                </tr>
                <tr>
                    <td>浏览学生</td>
                </tr>
            </table>
        </div>
    </body>
    </html>
    
    result.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>操作结果</title>
    </head>
    <body>
    result.jsp结果页面,注册结果: ${tips}
    </body>
    </html>
    
    addStudent.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%
    String basePath = request.getScheme() + "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
    %>
    <html>
    <head>
    <title>添加学生</title>
    <base href="<%=basePath%>"/>
    </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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
            <td><input type="submit" value="注册"></td>
        </tr>
    </table>
    </form>
    </div>
    </body>
    </html>
    
运行结果
index页面

首页显示

addStudent页面

注册中...

result页面

成功提示

数据库

数据库添加成功


通过ajax来实现查询功能

首先在webapp下创建一个叫js的文件夹,在里面我们放入jQuery的库文件
用1.x版本的最好,大公司都是用1.x的
要检查pom文件中是否将jackson的依赖加入

我们要实现的是,按下浏览学生的按钮后,跳转到新的页面显示数据库中学生的信息

index.jsp(部分)
<td><a href="listStudent.jsp">浏览学生</a></td>
控制器方法
@RequestMapping("student/queryStudent.do")
    @ResponseBody
    public List<Student> queryStudent(){//查询处理,响应ajax
        //参数检查,简单的数据处理
        List<Student> students=studentService.findStudent();
        return students;
    }
listStudent.jsp(结果页面)
<%
    String basePath = request.getScheme() + "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>使用ajax查询学生</title>
    <base href="<%=basePath%>"/>
    <script src="js/jquery-3.5.1.js"></script>
    <script type="text/javascript">

        //在当前页面dom对象加载后,执行loadStudentData()
        loadStudentData();

        $(function () {
            $("#btnLoader").click(function () {
                loadStudentData();
            })
        })
        
        function loadStudentData() {
            $.ajax({
                url:"student/queryStudent.do",
                type:"get",
                dataType:"json",
                success:function (data) {
                    //alert("data"+data)

                    //清楚旧的数据
                    $("#info").html("");
                    //增加新的数据
                    $.each(data,function (i,n) {
                        $("#info").append("<tr>")
                            .append("<td>"+n.id+"</td>")
                            .append("<td>"+n.name+"</td>")
                            .append("<td>"+n.age+"</td>")
                            .append("</tr>")
                    })
                }
            })
        }

    </script>
</head>
<body>

    <div align="center">
        <table>
            <thead>
                <tr>
                    <td>学号</td>
                    <td>姓名</td>
                    <td>年龄</td>
                </tr>
            </thead>
            <tbody id="info">

            </tbody>
        </table>
        <input type="button" id="btnLoader" value="查询数据">
    </div>

</body>
</html>
运行结果
点击按钮

浏览学生

显示结果

按下按钮会刷新数据内容

接受请求流程

流程图示

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值