SSM 整合 学习记录

MyBatis

👉 https://www.cnblogs.com/piggyyy/p/16870103.html

Spring

👉 https://www.cnblogs.com/piggyyy/p/16893370.html

SpringMVC

👉 https://www.cnblogs.com/piggyyy/p/16901245.html

SSM 整合

1新建项目并引入依赖

新建maven项目并选择archetype :maven-archetype-webapp

修改项目Java依赖版本为8,编译器jdk为8版本

FileEncoding什么的编码设置成UTF-8

根据需要创建包

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring.version>5.3.15</spring.version>
</properties>
<dependencies>
<!--    测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--    SpringMVC-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--    事务管理器需要-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--    MyBatis核心-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
    </dependency>
    <!--    MyBatis和Spring的整合包-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.7</version>
    </dependency>
    <!--    连接池-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.22</version>
    </dependency>
    <!--    MySQL驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.29</version>
    </dependency>
    <!--    日志-->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.3.0-alpha14</version>
    </dependency>
    <!--    分页插件-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.3.0</version>
    </dependency>
    <!--ServletAPI-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <!--    SpringMVC处理json数据-->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.4.2</version>
    </dependency>
    <!--    文件上传,下载不需要-->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>
    <!--    Spring和Thymeleaf的整合包-->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
        <version>3.0.11.RELEASE</version>
    </dependency>
</dependencies>

2数据库&表

数据库名:db_learn

表名:tb_user

CREATE TABLE tb_user (
id int NOT NULL AUTO_INCREMENT,
username varchar(255) DEFAULT NULL,
password varchar(255) DEFAULT NULL,
mail varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;

3配置web.xml

注意标签有顺序要求

<!--  Spring配置文件位置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
</context-param>
<!--  spring编码过滤器-->
<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>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<!--  处理请求方式的过滤器-->
<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<!--  Spring的监听器,在服务器启动时加载Spring的配置文付-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--  SpringMVC的前端控制器-->
<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>
    <!--    DispatcherServlet初始化时间提前到服务器启动时-->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

4配置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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--    扫描组件-->
    <context:component-scan base-package="com.ssm.controller"/>
    <!--    视图解析器-->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!--视图前缀-->
                        <property name="prefix" value="/templates/"/>
                        <!--视图后缀-->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
    <!--    默认servlet处理静态资源-->
    <mvc:default-servlet-handler/>
    <!--    开启mvc注解驱动-->
    <mvc:annotation-driven/>
    <!--    视图控制器-->
    <mvc:view-controller path="/" view-name="index"/>
    <!--    文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
    <!--    按需配置拦截器和异常解析器,详见 https://www.cnblogs.com/piggyyy/p/16901245.html 查看对应部分配置-->
</beans>

5配置Tomcat

启动服务器并访问http://localhost:8080/ 能否成功跳转至index页,可以说明mvc配置成功

6配置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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--扫描组件 控制层除外-->
    <context:component-scan base-package="com.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--    引入properties-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--    数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--    sqlSessionFactoryBean, 可以直接在Spring的IOC中获取SqlSess ionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--        设置MyBatis的核心配置文件的路径-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--        数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    配置mapper接口的扫描,可以将指定包下所有的mapper接口,通过sqlSession创建代理实现类对象,并将这些对象交给IOC容器管理(直接使用,不用再创建SqlSession获取bean实例)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm.mapper"/>
    </bean>
<!--    配置事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    事务注解驱动 默认 transaction-manager="transactionManager" 不用配置-->
    <tx:annotation-driven />
</beans>

properties文件,根据实际设置(Driver是mysql8.x版本的,5.x去掉cj)

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=
jdbc.username=
jdbc.password=

7配置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="mapUnderscoreToCamelCase" value="true"/>
    </settings>
<!--    类型别名-->
    <typeAliases>
        <package name="com.ssm.bean"/>
    </typeAliases>
    <!--    分页插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
    </plugins>
<!--    连接数据库环境?因为已经交给Spring管理,这里无需再设置-->
<!--    mybatis映射文件-->
    <mappers>
        <package name="com.ssm.mapper"/>
    </mappers>
</configuration>

8配置log4j

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m($F:%L) \n"/>
        </layout>
    </appender>
    <logger name="java:sql">
        <level value="debug"/>
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info"/>
    </logger>
    <root>
        <level value="debug"/>
        <appender-ref ref="STDOUT"/>
    </root>
</log4j:configuration>

9SSM示例代码

User

public class User {
    private Integer id;
    private String username;
    private String password;
    private String mail;
	// setter getter... 
}

UserController

@Controller
public class UserController {
    @Resource
    private UserService userService;
    @RequestMapping(value = "/user/page/{pn}", method = RequestMethod.GET)
    public String getUserPage(@PathVariable("pn") Integer pn, Model model) {
        PageInfo<User> page = userService.getUserPage(pn);
        model.addAttribute("page", page);
        return "user-list";
    }
}

UserService

public interface UserService {
    List<User> getAllUser();
    PageInfo<User> getUserPage(Integer pn);
}

UserServiceImpl

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }
    @Override
    public PageInfo<User> getUserPage(Integer pn) {
        PageHelper.startPage(pn, 10);
        List<User> userList = userMapper.getAllUser();
        return new PageInfo<>(userList, 5);
    }
}

UserMapper

<?xm1 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.ssm.mapper.UserMapper">
    <select id="getAllUser" resultType="User">
        SELECT id,username,mail FROM `tb_user`
    </select>
</mapper>

user-list.html

<table class="primary" style="display: inline-block">
    <tr>
        <th colspan="5">用户列表</th>
    </tr>
    <tr>
        <th>序号</th>
        <th>用户ID</th>
        <th>用户名</th>
        <th>邮箱</th>
        <th>操作</th>
    </tr>
    <tr th:each="user,status : ${page.list}">
        <td th:text="${status.count}"></td>
        <td th:text="${user.id}"></td>
        <td th:text="${user.username}"></td>
        <td th:text="${user.mail}"></td>
        <td>
            <a href="">修改</a>
            <a href="">删除</a>
        </td>
    </tr>
</table>
<div style="text-align: center" id="nav">
    <a th:if="${page.hasPreviousPage}" th:href="@{/user/page/1}">首页</a>
    <a th:if="${page.hasPreviousPage}" th:href="@{'/user/page/' + ${page.prePage}}">上一页</a>
    <span th:each="num : ${page.navigatepageNums}">
        <a th:if="${page.hasNextPage}" th:href="@{'/user/page/' + ${num}}" th:text="'[' + ${num} + ']'"></a>
    </span>
    <a th:if="${page.hasNextPage}" th:href="@{'/user/page/' + ${page.nextPage}}">下一页</a>
    <a th:if="${page.hasNextPage}" th:href="@{'/user/page/' + ${page.pages}}">尾页</a>
</div>

http://localhost:8080/user/page/2

learn from https://www.bilibili.com/video/BV1Ya411S7aT

  • MyBatisGenerator生成重复java文件

posted @ 2022-11-18 03:24  夏末秋初~  阅读(3)  评论(0编辑  收藏  举报