整合SSM

Posted sky1023

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了整合SSM相关的知识,希望对你有一定的参考价值。

整合SSM

1.环境搭建

  1. 导入相关的pom依赖
        <!-- jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <!--fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
    <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
<!--        spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <!--Servlet - JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <!--servlet-api导入高版本的-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

  1. Maven资源过滤设置
<build>
   <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
       <resource>
           <directory>src/main/resources</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
   </resources>
</build>
  1. 建立基本结构

java目录下

  • com.lgw.dao
  • com.lgw.pojo
  • com.lgw.service
  • com.lgw.controller

resources目录下

  • mapper
  • mybatis
  • spring
  1. 配置框架

mybatis目录下:mybatis-config.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>

</configuration>

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

</beans>

Spring目录下:spirng-dao.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">


</beans>

Spring目录下:spirng-service.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">


</beans>

Spring目录下:spirng-mvc.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-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

</beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root

log4j ....

2.Mybatis层

Mybatis-config.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="lazyLoadingEnabled" value="true"/>
        <!--        开启驼峰映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/> 
    </settings>
    <!-- 别名   -->
    <typeAliases>
        <package name="com.lgw.pojo"/>
    </typeAliases>
</configuration>

pojo实体类(在此省略方法)

package com.lgw.pojo;

public class Admin {
    private int adminId;
    private String adminName;
    private String adminPassword;
}

dao层Mapper接口

package com.lgw.dao.admin;


import com.lgw.pojo.Admin;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface AdminMapper {
    /**
     * 查询所有管理员
     * @return
     */
    List<Admin>  QueryAdmins();


    Admin QueryAdminById(@Param("id") int id);
    /**
     * 增加一个管理员
     * @param admin
     * @return
     */
    int addAdmin(Admin admin);

    /** 删除一个管理员
     * @param id
     * @return
     */
    int deleteAdmin(@Param("id") int id);

    /** 删除一个管理员
     * @param map
     * @return
     */
    int updateAdmin(Map map);
}

对应的*Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lgw.dao.admin.AdminMapper">

    <select id="QueryAdmins" resultType="Admin">
     select admin_id,admin_name,admin_password from admin
 </select>

    <select id="QueryAdminById" resultType="Admin">
   select admin_id,admin_name,admin_password from admin where admin_id=#{id}
</select>

    <insert id="addAdmin" parameterType="Admin">
  insert into admin values(admin_name,admin_password)
</insert>

    <delete id="deleteAdmin">
    delete from admin where admin_id=#{id}
</delete>

    <update id="updateAdmin" parameterType="map">
    update admin set  admin_name=#{name} admin_password=#{password}
    WHERE admin_id = #{id}
</update>
</mapper>

编写Service层的接口和实现类

接口

package com.lgw.service.admin;

import com.lgw.pojo.Admin;
import java.util.List;
import java.util.Map;

public interface AdminService {
    /**
     * 查询所有管理员
     * @return
     */
    List<Admin> QueryAdmins();

    Admin QueryAdminById( int id);

    /**
     * 增加一个管理员
     * @param admin
     * @return
     */
    int addAdmin(Admin admin);

    /** 删除一个管理员
     * @param id
     * @return
     */
    int deleteAdmin(int id);

    /** 删除一个管理员
     * @param map
     * @return
     */
    int updateAdmin(Map map);
}

实现类

package com.lgw.service.admin;

import com.lgw.dao.admin.AdminMapper;
import com.lgw.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


public class AdminServiceImpl implements AdminService {
//    service层调dao层

    private AdminMapper adminMapper;

    public void setAdminMapper(AdminMapper adminMapper) {
        this.adminMapper = adminMapper;
    }

    public List<Admin> QueryAdmins() {
        return adminMapper.QueryAdmins();
    }

    public Admin QueryAdminById(int id) {
        return adminMapper.QueryAdminById(id);
    }

    public int addAdmin(Admin admin) {
        return adminMapper.addAdmin(admin);
    }

    public int deleteAdmin(int id) {
        return adminMapper.deleteAdmin(id);
    }

    public int updateAdmin(Map map) {
        return adminMapper.updateAdmin(map);
    }
}

3.Spring层

整合Mybtais配置文件

spring-dao.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">
    <!--1.关联数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--2.连接池,数据源  dbcp,半自动 不能自动连接
                    c30,自动化操作
                    druid, hikari
-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--  3.  sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--       映射数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--  引入Mybatis-config.xml配置文件-->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
        <!--       引入 *Mapper.xml配置文件-->
        <property name="mapperLocations" value="classpath:mapper/AdminMapper.xml"/>
    </bean>
    <!--    4. 配置dao接口扫描包,动态注入Spring容器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.lgw.dao"/>
    </bean>
</beans>

Mapper接口加注解,纳入Spring管理

@Repository
public interface AdminMapper {

}

Spring整合Service层

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

    <!-- 1.扫描service相关的bean -->
    <context:component-scan base-package="com.lgw.service" />

    <!--3.配置声明式事物-->
    <bean id="DataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 4.aop事物支持-->

    </beans>

Service层实现类注解

@Service
public class AdminServiceImpl implements AdminService {
//    service层调dao层
    @Autowired
    @Qualifier("adminMapper")
    private AdminMapper adminMapper;
    }

4.SpringMVC层

  1. 配置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">
<!--    设置默认启动页-->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!--1.注册DispatcherServlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--配置SpringMVC过滤-->
    <!-- 配置过滤器-->
    <filter>
        <filter-name>encoding-fiflter</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>
    </filter>
    <filter-mapping>
        <filter-name>encoding-fiflter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
<!-- 3.配置session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>
  1. spring-mvc.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-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 开启包扫描,并注册注解 -->
    <context:component-scan base-package="com.lgw.controller"/>
    <!--让spring不在处理静态资源-->
    <mvc:default-servlet-handler/>
    <!--解决json 乱码配置-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--视图解析器:DispatcherServlet给他的ModelAndView-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/view/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

<!--    拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.lgw.filter.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
    <!--文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--        设置编码格式 默认ISO-8859-1-->
    <property name="defaultEncoding" value="UTF-8"/>
    <!--上传大小上限,单位字节 10485760=10M-->
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
   </bean>

</beans>
  1. 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"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

   <import resource="spring-dao.xml"/>
   <import resource="spring-service.xml"/>
   <import resource="spring-mvc.xml"/>
   
</beans>
  1. 代码编写

controller层

package com.lgw.controller;

import com.lgw.pojo.Admin;
import com.lgw.service.admin.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class AdminController {
//    Controller 调用service
    @Autowired
    @Qualifier("adminServiceImpl")
    private AdminService adminService;
    @RequestMapping("/admin/all")
    public String allAdmins(Model model){
        List<Admin> admins = adminService.QueryAdmins();
        model.addAttribute("admins",admins);
        return "Admins";
    }
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
   <title>首页</title>
   <style type="text/css">
       a {
           text-decoration: none;
           color: black;
           font-size: 18px;
      }
       h3 {
           width: 180px;
           height: 38px;
           margin: 100px auto;
           text-align: center;
           line-height: 38px;
           background: deepskyblue;
           border-radius: 4px;
      }
   </style>
</head>
<body>

<h3>
   <a href="${pageContext.request.contextPath}/admin/all">查询管理员</a>
</h3>
</body>
</html>

在web-inf下创建view/Admin.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${admins}
</body>
</html>

基本的SSM框架搭建成功,开始测业务了

以上是关于整合SSM的主要内容,如果未能解决你的问题,请参考以下文章

SSM框架整合

SSM 项目整合详细解读

SSM整合

520前,我放弃陪女朋友时间,被迫写代码:“SSM框架整合+excel文件上传到数据库+数据更新“

shiro整合SSM(spring_springmvc_mybatis)

ssm整合redis