SSM整合开发

目录

SSM基本介绍

springmvc和spring两者容器的关系

SSM实现步骤

SSM实现步骤(附代码)

1.使用springdb(数据库名称)的mysql数据库,表使用student。

2.新建maven web项目。

3.在pom.xml中添加依赖。(springmvc,spring,mybatis,jackson,mysql驱动,druid连接池,jsp,servlet)

4.写web.xml。

               1)注册  DispatchServlet(中央处理器/前端控制器)

               2)注册spring的 ContextLoaderListerner  (监听器)

               3)注册字符集过滤器

5.创建包(项目结构):controller,service,dao,实体类包名创建好   

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

                1)springmvc配置文件

                2) spring配置文件

                3)mybatis配置文件

                4)数据库属性文件

7.写代码,dao接口和mapper文件,service和实现类,controller,实体类。

8.写jsp页面。


SSM基本介绍

SpringMVC:视图层,界面层。负责接收用户请求,显示处理结果的。

Spring:业务层。管理service,dao,工具类对象的。

MyBatis:持久层。访问数据库的。

SSM也叫SSI(IBatis是MyBatis的前身),整合中有容器:

        1.SpringMVC容器:管理Contorller控制器对象的。

        2.Spring容器:管理Service,dao工具类对象的。

我们要做的就是把使用的对象交给合适的容器进行创建,管理。

        1.把Contorller还有web开发的相关对象交给springmvc容器,这些web用的对象,写到springmvc的配置文件中。

        2.把service和dao对象定义到spring的配置文件中,让spring管理这些对象。

springmvc和spring两者容器的关系

springmvc容器是spring容器的子容器,类似于java中的继承(但不是)

子容器可以访问父容器中的内容:

        springmvc子容器中的Controller可以访问spring父容器中的Service对象,就可以实现controller可以使用service对象了。

SSM实现步骤

  1. 使用springdb(数据库名称)的mysql数据库,表使用student。
  2. 新建maven web项目。
  3. 在pom.xml中添加依赖。(springmvc,spring,mybatis,jackson,mysql驱动,druid连接池,jsp,servlet)
  4. 写web.xml。

               1)注册  DispatchServlet(中央处理器/前端控制器)

                        目的: ①创建springmvc容器对象,才能创建Controller类对象

                                    ②创建Servlet,才能接受用户请求。

               2)注册spring的 ContextLoaderListerner  (监听器)

                        目的:创建spring的容器对象,才能创建service和dao对象。

               3)注册字符集过滤器

                        目的:解决post请求乱码问题。

    5.创建包(项目结构):controller,service,dao,实体类包名创建好       

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

                1)springmvc配置文件

                2) spring配置文件

                3)mybatis配置文件

                4)数据库属性文件

    7.写代码,dao接口和mapper文件,service和实现类,controller,实体类。

    8.写jsp页面。

SSM实现步骤(附代码)

1.使用springdb(数据库名称)的mysql数据库,表使用student。

        

2.新建maven web项目。

3.在pom.xml中添加依赖。(springmvc,spring,mybatis,jackson,mysql驱动,druid连接池,jsp,servlet)

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bjpowernode</groupId>
    <artifactId>ch06-SSM</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>

    <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>
    <!--servlet依赖-->
    <dependencies>
        <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>
        <!--        springmvc依赖-->
        <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>
        <!--        jackson-->
        <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>
        <!--        mybatis-spring整合-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--        mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <!--        druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>ch06-SSM</finalName>
        <resources>
            <resource>
                <directory>src/main/java</directory><!--所在的目录-->
                <includes>
                    <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>
</project>

4.写web.xml。

               1)注册  DispatchServlet(中央处理器/前端控制器)

                        目的: ①创建springmvc容器对象,才能创建Controller类对象

                                    ②创建Servlet,才能接受用户请求。

               2)注册spring的 ContextLoaderListerner  (监听器)

                        目的:创建spring的容器对象,才能创建service和dao对象。

               3)注册字符集过滤器

                        目的:解决post请求乱码问题。

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

    <!--1)注册ContextLoaderListener监听器
                注册ServletContext监听器的实现类ContextLoaderListener,
                用于创建Spring容器及将创建好的Spring容器对象放入到ServletContext的作用域中。
        2)注册字符集过滤器
                注册字符集过滤器,用于解决请求参数中携带中文时产生乱码问题。
        3)配置中央调度器
       -->
    <!--声明spring监听器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:conf/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--字符集过滤器,解决psot乱码-->
    <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>
            <!--强制请求(request)对象使用encoding的编码方式-->
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
             <!--强制应答(response)对象使用encoding的编码方式-->
            <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>

     <!--声明springmvc的核心对象

        访问mymvc地址后, 报错 文件没有找到。找的文件 /WEB-INF/springmvc-servlet.xml
                                                  /WEB-INF/myweb-servlet.xml
        错误原因:
           在Servlet的init()方法中,创建springmvc使用的容器对象WebApplicationContext.
           WebApplicationContext ctx = new ClassPathXmlApplicationContext(配置文件)。
           配置文件的默认路径: /WEB-INF/<servlet-name>-servlet.xml

    -->
    <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/dispatcherServlet.xml</param-value>
        </init-param>
        <!--
           表示服务器tomcat创建对象的顺序, 是个整数值, 大于等于0.
           数值越小,创建对象的时间越早。
        -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!--
           url-pattern 作用: 把一些请求交给指定的servlet处理
           使用中央调度器(DispatcherServlet)
           1. 使用扩展名方式, 格式 *.xxx ,  xxx是自定义的扩展名。
              例如  *.do , *.action, *.mvc 等等. 不能使用*.jsp
              http://localhost:8080/myweb/some.do
              http://localhost:8080/myweb/user/list/queryUser.do
              http://localhost:8080/myweb/user/list/list.do

           2. 使用斜杠 "/"
        -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

5.创建包(项目结构):controller,service,dao,实体类包名创建好   

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

                1)springmvc配置文件

<?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的配置文件-->
    <!--声明组件扫描器-->
    <context:component-scan base-package="com.bjpowernode.controller" />

    <!--声明视图解析器:帮助处理视图-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀:指定视图文件的路径-->
        <property name="prefix" value="/WEB-INF/view/" />
        <!--后缀:视图文件的扩展名-->
        <property name="suffix" value=".jsp" />
    </bean>

    <!--声明注解驱动:创建HttpMessageConverter接口的7个实现类对象
        ajax和处理静态资源都需要用到-->
    <mvc:annotation-driven />
</beans>

                2) spring配置文件

<?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.code.service"/>

    <!--    引入jdbc.properties-->
    <context:property-placeholder location="classpath:conf/jdbc.properties"/>
<!--    通过druid连接池连和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.code.dao"/>
    </bean>

    <!--事务配置-->
</beans>

                3)mybatis配置文件

<?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>
        <!--domain包中的类名就是别名-->
        <package name="com.bjpowernode.domain" />
    </typeAliases>

    <mappers>
        <!--加载dao包中的所有mapper文件-->
       <package name="com.bjpowernode.dao" />
    </mappers>
</configuration>

                4)数据库属性文件

jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.username=root
jdbc.password=root

7.写代码,dao接口和mapper文件,service和实现类,controller,实体类。

controller

package com.code.controller;

import com.code.domain.Student;
import com.code.service.StudentService;
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.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/student")     //组
public class StudentController {

    /**
     声明引用类型, 调用引用类型的业务方法
     引用类型自动注入  @Autowired, @Resource
     */
    @Resource
    private StudentService service;

    //添加学生
    @RequestMapping("/addStudent.do")
    public ModelAndView addStudent(Student student){
        ModelAndView mv  = new ModelAndView();

        //调用service,处理业务逻辑,把处理结果返回给用户
        int rows  = service.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 = service.queryStudents();
        return students;
    }
}

dao

package com.code.dao;

import com.code.domain.Student;

import java.util.List;

public interface StudentDao {
    int insertStudent(Student student);
    List<Student> selectStudents();
}
<?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.code.dao.StudentDao">
    <!-- 使用insert, update,delete,select标签写sql -->

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

    <select id="selectStudents"  resultType="com.code.domain.Student">
        select * from student order by id desc
    </select>
</mapper>

 domain

package com.code.domain;

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {
        return name;
    }

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

    public int getId() {
        return id;
    }

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

    public Integer getAge() {
        return age;
    }

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

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

service

package com.code.service;

import com.code.domain.Student;
import java.util.List;

public interface StudentService {

    int addStudent(Student student);
    List<Student> queryStudents();
}


=======================================

package com.code.service.Impl;

import com.code.dao.StudentDao;
import com.code.domain.Student;
import com.code.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 studentDao;


    @Override
    public int addStudent(Student student) {
        int i = studentDao.insertStudent(student);
        return i;
    }

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

8.写jsp页面。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme() + "://" + request.getServerName()
            +":"+request.getServerPort()+request.getContextPath()+"/";
%>
<%--配置可变url--%>
<html>
<head>
    <title>SSM</title>
    <base href="<%=basePath%>">
</head>
<body>
    <div align="center">
        <p>SSM整合开发的例子</p>
        <table>
            <tr>
                <td><a href="addStudent.jsp">注册学生</a> </td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td><a href="listStudent.jsp">查看学生</a> </td>
            </tr>
        </table>
    </div>
</body>
</html>

=======================================================================================


<%@ 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>注册学生</p>
        <form action="student/addStudent.do">
            <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>


=========================================================================================

<%@ 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%>">
    
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>

    <script type="text/javascript">
        $(function () {
            //在页面加载后,执行ajax,异步获取数据
            getStudentInfo();

            $("#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.email + "</td><td>"
                            + n.age + "</td></tr>");
                    })
                }
            })
        }
    </script>

</head>
<body>
<div align="center">
    <p>浏览学生
        <button id="doAjax">获取学生数据</button>
    </p>
    <table>
        <thead>
        <tr>
            <td>id</td>
            <td>姓名</td>
            <td>邮箱</td>
            <td>年龄</td>
        </tr>
        </thead>
        <tbody id="stuinfo">
        </tbody>
    </table>
</div>
</body>
</html>

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值