Bootstrap

SSM整合(教你快速搭建一个ssm项目)

SSM整合(教你快速搭建一个ssm项目)

一、基本环境搭建

1.创建一个maven项目

相信各位大佬都会<(^-^)>

2.导入相关依赖

所有依赖都在这里汇总了,后面就不多说

<!--数据库-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.22</version>
</dependency>
<!--连接池c3po dbcp druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.1</version>
</dependency>
<!--mybatis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.5</version>
</dependency>
<!-- mybatis-spring整合 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.5</version>
</dependency>
<!-- aspectJ AOP 织入器 -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
</dependency>
<!--Spring-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.10.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.10.RELEASE</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>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.16</version>
</dependency>
<!--log4j2-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.30</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>
<!--Junit-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>RELEASE</version>
    <scope>compile</scope>
</dependency>
<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.72</version>
</dependency>

为避免资源导出问题可以添加以下代码

<!--静态资源导出问题-->
<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>
3.建表

建一个user表

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int NOT NULL,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `age` int NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
4.实体类(src/main/java/)

这里用了lombok,省去了get、set方法,简洁多了

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private Integer id;
    private String name;
    private Integer age;

}
5.Dao接口
@Repository
public interface UserDao {

    public void addUser(User user);

    public int deleteUserById(@Param("id") int id);

    public int updateUser(User user);

    public List<User> queryAll();

    public User queryById(@Param("id") int id);
}
6.Mapper配置文件(src/main/resources/mapper/)

除了使用mapper.xml文件编写sql语句,还可以使用注解注入sql语句,这里我用的是配置文件。

<?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.zzy.dao.UserDao">

    <insert id="addUser" parameterType="User">
        insert into user values(#{id},#{name},#{age})
    </insert>

    <delete id="deleteUserById" parameterType="int">
        delete from user where id = #{id}
    </delete>

    <update id="updateUser" parameterType="User">
        update user set id=#{id},name=#{name},age=#{age}
    </update>

    <select id="queryAll" resultType="User">
        select * from user
    </select>

    <select id="queryById" resultType="User">
        select * from user where id = #{id}
    </select>
</mapper>
7.Service接口
public interface UserService {

    public void addUser(User user);

    public int deleteUserById(int id);

    public int updateUser(User user);

    public List<User> queryAll();

    public User queryById(int id);
}
8.Service接口实现类
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;


    @Override
    public List<User> queryAll() {
        System.out.println("======================service业务层,显示所有用户======================");
        return userDao.queryAll();
    }

    @Override
    public User queryById(int id) {
        return null;
    }

    @Override
    public void addUser(User user) {
        System.out.println("====================service业务层,保存用户========================");
        userDao.addUser(user);
    }

    @Override
    public int deleteUserById(int id) {
        return 0;
    }

    @Override
    public int updateUser(User user) {
        return 0;
    }

}

二、spring环境搭建

1.applicationContext.xml配置文件(src/main/resources/)
<?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 http://www.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.zzy">
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
</beans>
2.SpringTest测试类(src/main/java/com/zzy/test/)
public class SpringTest {
    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.queryAll();
    }
}

后台打印输出“service业务层,显示所有用户”,则spring环境搭建成功!

三、mybatis环境搭建

1.dao接口和mapper.xml配置文件

mybatis环境搭建首先要编写dao接口和mapper.xml核心配置文件,前面已经说过了,这里就不重复了。

2.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>
    
    <typeAliases>
        <package name="com.zzy.pojo"/>
    </typeAliases>
    
    <!--数据库环境配置,后面sm整合时并入applicationContext.xml中可以去掉-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/study?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
    <!--注册mapper.xml的位置-->
    <mappers>
        <package name="com.zzy.dao"/>
    </mappers>
    
</configuration>
3.MybatisTest测试类
public class MybatisTest {
    @Test
    public void test1() throws IOException {
        InputStream in = Resources.getResourceAsStream("applicationContext.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);
        List<User> userList = dao.queryAll();
        for (User user:userList) {
            System.out.println(user);
        }
        sqlSession.close();
        in.close();
    }
    @Test
    public void test2() throws IOException {
        User user = new User();
        user.setId(3);
        user.setName("小芳");
        user.setAge(20);
        //加载配置文件
        InputStream in = Resources.getResourceAsStream("applicationContext.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //创建sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取到代理对象
        UserDao dao = sqlSession.getMapper(UserDao.class);
        //保存
        dao.addUser(user);
        //提交事务
        sqlSession.commit();
        //关闭资源
        sqlSession.close();
        in.close();
    }
}

四、sm整合(spring+mybatis)

1.整合思路

​ Service能成功调用dao对象,能够做查询操作或者新增数据能存进数据库即为整合成功。要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:一个 SqlSessionFactory 和至少一个数据映射器类。在 MyBatis-Spring 中,可使用 SqlSessionFactoryBean 来创建 SqlSessionFactory,SqlSessionFactory 唯一的必要属性是 DataSource,一个常用的属性是 configLocation,它用来指定 MyBatis 的 XML 配置文件路径。SqlSessionTemplate 是 MyBatis-Spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession。模板可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用 SqlSessionTemplate 来替换 MyBatis 默认的 DefaultSqlSession 实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。可以使用 SqlSessionFactory 作为构造方法的参数来创建 SqlSessionTemplate对象。

2.在applicationContext.xml 文件中整合 mybatis

​ 整合步骤:

  • 开启注解扫描
  • 创建数据源dataSource(这里配置了mybatis-config.xml中的数据库环境,可以去掉environments里的内容了)
  • 创建SqlSessionFactory
  • 创建DAO
  • 创建事务管理器
<?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:component-scan base-package="com.zzy">
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

<!-- 整合:spring 接管 mybatis 中配置SqlSessionFactory对象的创建-->
    <!-- 数据源druid-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/study?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!-- 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!--关联Mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 扫描sql配置文件:Dao对应的*mapper.xml文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
    <bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入SqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 扫描DAO接口所在包 -->
        <property name="basePackage" value="com.zzy.dao"/>
    </bean>
    
        <!--配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>

    <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>

</beans>

五、springmvc环境搭建

1.在web.xml中配置DispatherServlet前端控制器
<!--配置前端控制器-->
<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:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

设置拦截器,解决乱码问题

<!--设置字符集拦截器,解决中文乱码问题-->
<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>
</filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<!--设置RestFul风格拦截器-->
<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
2.引入springmvc.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.alibaba.com/schema/stat"
       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.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd">

    <context:component-scan base-package="com.zzy.controller"/>

    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
</beans>
3.编写controller代码
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/queryAll")
    public String findAll(Model model){
        System.out.println("========================Controller层,查询所有用户=================");
        List<User> list = userService.queryAll();
        model.addAttribute("list",list);
        return "hello";
    }

    @RequestMapping("/addUser")
    public void save(User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("========================Controller层,保存用户=================");
        userService.addUser(user);
        response.sendRedirect(request.getContextPath()+"/user/queryAll");
        return;
    }
}
4.创建jsp页面

index.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="user/queryAll">查询所有用户</a>

    <form action="user/addUser" method="post">
        ID:<input type="text" name="id"/><br>
        姓名:<input type="text" name="name"/><br>
        年龄:<input type="text" name="age"/><br>
        <input type="submit" value="保存"><br>
    </form>
</body>
</html>

jsp/hello.jsp页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>所有用户</title>
</head>
<body>
    <h1>已查询所有用户</h1>
    <c:forEach items="${list}" var="user">
        ${user.name}
    </c:forEach>
</body>
</html>
5.部署tomcat服务器测试

六、ss整合(spring+springmvc)

1.整合思路

在controller(SpringMVC)中能成功的调用service(Spring)对象中的方法即为整合成功。要想在controller中调用service方法,就要注入service到controller中来,有service对象才可以调用service方法。现在我们启动Tomcat之后,因为web.xml中配置了前端控制器,web容器会帮我们加载springmvc.xml配置文件,但在springmvc.xml配置文件中我们是只扫描controller,别的不扫。所以applicationContext.xml文件就从头到尾没有执行过,applicationContext中的配置扫描自然也不会去扫描,就相当于没有将spring交到IOC容器当中去。那么,怎么在启动服务器时去加载applicationContext配置文件呢?这时候我们就需要配置监听器了。

2.在web.xml中配置ContextLoaderListener监听器
<!--配置spring的监听器-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--设置applicationContext.xml配置文件的路径-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
3.编写Controller代码

在controller中注入service

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/queryAll")
    public String queryAll(Model model){
        System.out.println("========================Controller层,查询所有用户=================");
        List<User> userList = userService.queryAll();
        model.addAttribute("userList",userList);
        return "user";
    }

    @RequestMapping("/addUser")
    public void addUser(User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("========================Controller层,保存用户=================");
        userService.addUser(user);
        response.sendRedirect(request.getContextPath()+"/user/queryAll");
    }
}
4.启动tomcat测试

如果可以出现页面并且点击保存后台输出“Controller层…”,则spring、springmvc整合成功!

;