SSM框架整合开发入门详解

SSM框架整合开发

依赖\插件

  <dependencies>
    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- spring核心依赖 ioc的 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--spring aop的-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--spring事务的-->
    <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>
    <!-- mysql驱动 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <!-- mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>
    <!-- spring集成mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!-- 数据库连接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>
    <!-- servlet依赖 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- springMVC -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--jackson依赖-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
  </dependencies>
  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>

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:mvn="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.wm.controller"/>

    <!--逻辑视图前缀后缀-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--注解驱动1、响应ajax返回json;2、静态资源-->
    <mvn:annotation-driven/>

</beans>

数据库连接配置文件

jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf-8&amp;useSSL=false
jdbc.username=root
jdbc.password=root
jdbc.maxActive=20

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

    <!--数据库配置文件-->
    <context:property-placeholder location="classpath:config/jdbc.properties"/>
    <!--声明数据源:druid连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <!--set注入给druid提供数据库连接信息-->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="${jdbc.maxActive}"/>
    </bean>

    <!--声明SqlSessionFactoryBean对象,这个类内部创建了SqlSessionFactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--这里将上面创建的dataSource对象赋给SqlSessionFactoryBean的DataSource属性-->
        <property name="dataSource" ref="dataSource"/>
        <!--mybatis主配置文件的位置-->
        <property name="configLocation" value="classpath:config/mybatis.xml"/>
    </bean>

    <!--mybatis扫描器,获取dao对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--这里sqlSessionFactoryBeanName的参数是String的
                因此只需要把SqlSessionFactory的对象名,也就是bean的id赋给他即可-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--指定包名MapperScannerConfigurer会扫描这个包下的所有接口,把每个接口都执行一次-->
        <property name="basePackage" value="com.wm.dao"/>
    </bean>

    <!--扫描器,扫描注解创建对象-->
    <context:component-scan base-package="com.wm.service"/>
</beans>

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>
        <!-- 设置mybatis输出日志 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--配置别名,mapper中resultType只需用类名-->
    <typeAliases>
        <!--实体类所在包-->
        <package name="com.wm.domain"/>
    </typeAliases>

    <mappers>
        <!-- 一次性加载这个包下的所有mapper.xml -->
        <!--使用要求:mapper和dao接口名一致,且在同一目录下-->
        <package name="com.wm.dao"/>
    </mappers>
</configuration>

web.xml配置

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

  <!--springMVC配置文件-->
  <servlet>
    <servlet-name>myweb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:config/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>

  <!--spring配置-->
  <!--指定读取的配置文件位置。-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:config/applicationContext.xml</param-value>
  </context-param>
  <!--注册监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--声明字符集过滤器-->
  <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>

</web-app>

结构示意图

在这里插入图片描述

实体类

package com.wm.domain;

public class User {

    Integer id;
    String name;
    Integer age;
    String address;

    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;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

dao层

UserDao.java

package com.wm.dao;

import com.wm.domain.User;

import java.util.List;

public interface UserDao {

    List<User> selectAll();
    int selectCount();

}

UserDao.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.wm.dao.UserDao">
    <select id="selectAll" resultType="User">
        select id,name,age,address from user
    </select>
</mapper>

service层

接口

package com.wm.service;

import com.wm.domain.User;

import java.util.List;

public interface UserService {

    List<User> queryAll();

}

实现类

package com.wm.service.impl;

import com.wm.dao.UserDao;
import com.wm.domain.User;
import com.wm.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserDao userDao;

    @Override
    public List<User> queryAll() {
        return userDao.selectAll();
    }
}

controller层

package com.wm.controller;

import com.github.pagehelper.PageHelper;
import com.wm.domain.User;
import com.wm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class UserController {
    @Resource
    private UserService userService;
    /*分页查询*/
    @ResponseBody
    @RequestMapping(value = "/pageSelect")
    public List<User> pageSelect(Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<User> users = userService.queryAll();
        return users;
    }
    /*查询全部*/
    @ResponseBody
    @RequestMapping(value = "/selectAll")
    public List<User> selectAll(){
        List<User> users = userService.queryAll();
        return users;
    }

}

前端jsp

<%--
  Created by IntelliJ IDEA.
  User: sshdg
  Date: 2020/8/11
  Time: 12:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $(function(){
            $("#selectPage-btn").click(function(){
                $.ajax({
                    url:"pageSelect",
                    type:"post",
                    data:{
                        pageNum : $('#pageNum').val(),
                        pageSize : $('#pageSize').val()
                    },
                    dataType:"json",
                    success:function (data) {
                        $("#list").html("")
                        $.each(data,function (i,n) {
                            $("#list").append("<tr>")
                                .append("<td>"+n.id+"</td>")
                                .append("<td>"+n.name+"</td>")
                                .append("<td>"+n.age+"</td>")
                                .append("<td>"+n.address+"</td>")
                                .append("</tr>")
                        })
                    }
                });
            });

            $("#selectAll-btn").click(function(){
                $.ajax({
                    url:"selectAll",
                    type:"post",
                    dataType:"json",
                    success:function (data) {
                        $("#list").html("")
                        $.each(data,function (i,n) {
                            $("#list").append("<tr>")
                                .append("<td>"+n.id+"</td>")
                                .append("<td>"+n.name+"</td>")
                                .append("<td>"+n.age+"</td>")
                                .append("<td>"+n.address+"</td>")
                                .append("</tr>")
                        })
                    }
                });
            });

        });
    </script>

</head>
<body>

    第几页:<input type="text"  id="pageNum"><br>
    每页几行:<input type="text"  id="pageSize"><br>
    <button id="selectPage-btn">分页查询</button><br>
    <button id="selectAll-btn">查询全部</button><br>

    <br><br>
    <table>
        <thead>
        <tr>
            <td>序号</td>
            <td>姓名</td>
            <td>年龄</td>
            <td>地址</td>
        </tr>
        </thead>
        <tbody id="list">

        </tbody>
    </table>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值