SpringMVC框架----->(4) SSM整合开发案例

SSM整合开发

1、搭建SSM开发环境

(1)在pom.xml中加入依赖和插件

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
  <!-- servlet依赖 -->
  <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-web</artifactId>
    <version>5.2.5.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.5.RELEASE</version>
  </dependency>
  <!--做spring事务依赖-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.2.3.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.3.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依赖-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.1</version>
  </dependency>
  <!--mybatis-spring集成依赖-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
  </dependency>
  <!--mysql驱动-->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
  </dependency>
  <!--连接池-->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.1</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>
  <!--指定jdk版本-->
  <plugins>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
  </plugins>
</build>

(2)配置web.xml文件

A、注册ContextLoaderListener监听器
  • 注册 ServletContext 监听器的实现类 ContextLoaderListener,用于创建 Spring 容器及将创建好的 Spring 容器对象放入到 ServletContext 的作用域中。
<!--注册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>
B、注册CharacterEncodingFilter字符集过滤器
<!--注册字符集过滤器-->
<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>
C、配置DispatcherServlet中央调度器
<!--中央调度器-->
<servlet>
  <servlet-name>myweb</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!--自定义springmvc读取的配置文件的位置-->
  <init-param>
    <!--springmvc的配置文件的位置的属性-->
    <param-name>contextConfigLocation</param-name>
    <!--指定自定义文件的位置-->
    <param-value>classpath:conf/dispatcherServlet.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>myweb</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

2、SSM整合注解开发

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

(1)建立stu表

在这里插入图片描述

(2)编写resources目录下的配置文件

A、jdbc属性配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3366/ssm?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
B、Spring配置文件applicationContext.xml
<!--引入属性配置文件-->
<context:property-placeholder location="classpath:conf/jdbc.properties" />
<!--声明数据源DataSource, 作用是连接数据库的-->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
      init-method="init" destroy-method="close">
    <!--set注入给DruidDataSource提供连接数据库信息 -->
    <!--    使用属性配置文件中的数据,语法 ${key} -->
    <property name="url" value="${jdbc.url}" /><!--setUrl()-->
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}" />
    <property name="maxActive" value="20" />
</bean>

<!--注册 SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--set注入,把数据库连接池付给了dataSource属性-->
    <property name="dataSource" ref="myDataSource" />
    <property name="configLocation" value="classpath:conf/mybatis.xml" />
</bean>

<!--注册mybatis的Mapper扫描器,创建dao对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--指定SqlSessionFactory对象的id-->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    <!--指定包名, 包名是dao接口所在的包名。
        MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行
        一次getMapper()方法,得到每个接口的dao对象。
        创建好的dao对象放入到spring的容器中的。 dao对象的默认名称是 接口名首字母小写
    -->
    <property name="basePackage" value="com.hcz.dao"/>
</bean>

<!--注册组件扫描器-->
<context:component-scan base-package="com.hcz.service"/>
C、SpringMVC配置文件dispatcherServlet.xml
<!--声明组件扫描器-->
<context:component-scan base-package="com.hcz.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/>
D、MyBatis配置文件mybatis.xml
<configuration>
    <!--mybatis.xml 文件加入日志配置,可以在控制台输出执行的 sql 语句和参数-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--设置别名-->
    <typeAliases>
        <package name="com.hcz.entity"/>
    </typeAliases>
    <!--sql映射文件的位置-->
    <mappers>
        <!--告诉mybatis要执行的sql语句的位置-->
        <package name="com.hcz.dao"/>
    </mappers>
</configuration>

(3)创建实体类Student

public class Student {
    
    

    private Integer id;
    private String name;
    private Integer age;
//这里省略set、get方法
}

(4)Dao接口和sql映射文件

public interface StudentDao {
    
    

    int insertStudent(Student student);
    List<Student> selectStudents();
}
<mapper namespace="com.hcz.dao.StudentDao">
    <select id="selectStudents" resultType="Student">
        select id,age,name from stu order by id desc
    </select>
    
    <insert id="insertStudent">
        insert into stu(name ,age) values (#{name},#{age})
    </insert>
</mapper>

(5)Service接口和实现类

public interface StudentService {
    
    

    int addStudent(Student student);
    List<Student> findStudents();
}
@Service
public class StudentServiceImpl implements StudentService {
    
    
    //引用类型自动注入@Autowired,@Resource
//byType
    @Resource
    private StudentDao studentDao;

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

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

(6)处理器定义

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

    @Resource
    private StudentService service;

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

        String tips = "注册失败";
        //调用service处理student
        int nums = service.addStudent(student);
        if(nums > 0){
    
    
            //注册成功
            tips = "学生【"+student.getName()+"】注册成功";
        }
        //添加数据
        mv.addObject("tips",tips);
        //指定结果页面
        mv.setViewName("result");
        return mv;
    }

    //处理查询,响应Ajax
    @RequestMapping("/queryStudent.do")
    @ResponseBody
    public List<Student> queryStudent(){
    
    
        //参数检查,简单的数据处理
        List<Student> students = service.findStudents();
        return students;
    }
}

(7)定义视图(首页面index.jsp)

<body>
    <div align="center">
        <p>SSM整合例子</p>
        <img src="images/ssm.jpg"/>
        <table>
            <tr>
                <td><a href="addStudent.jsp"> 注册学生</a></td>
            </tr>
            <tr>
                <td><a href="listStudent.jsp">浏览学生</a></td>
            </tr>
        </table>
    </div>
</body>

(8)注册学生页面(addStudent.jsp)

<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;&nbsp;</td>
                    <td><input type="submit" value="注册"></td>
                </tr>
            </table>
        </form>
    </div>
</body>

(9)浏览学生页面(listStudent.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme()+"://"+
            request.getServerName()+":"+request.getServerPort()+
            request.getContextPath()+"/";
%>
<html>
<head>
    <title>浏览学生Ajax</title>
    <base href="<%=basePath%>"/>
    <script type="text/javascript"src="js/jquery-3.4.1.js"></script>
    <script type="text/javascript">
        $(function(){
     
     
            //在当前页面dom对象加载后,执行loadStudentData()
            loadStudentData();

            $("#btnLoader").click(function(){
     
     
                //loadStudentData();
                alert($("#country > option:selected").val());

                alert($("#country > option:selected").text());
            })
        })

        function loadStudentData(){
     
     
            $.ajax({
     
     
                url:"student/queryStudent.do",
                type:"get",
                dataType:"json",
                success:function(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>

(10)结果页面(result.jsp)

<body>
    result.jsp结果页面,注册结果:${tips}
</body>

猜你喜欢

转载自blog.csdn.net/hcz666/article/details/113986557