Java教程

整合SSM的demo

本文主要是介绍整合SSM的demo,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

准备工作

  • 首先数据库的创建和数据的添加:

  • 新建一个Maven空项目,添加WEB应用程序框架支持,完成后如图:

  • 在POM中添加相关依赖:
<dependencies>
    <!--Junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    
    <!--数据库驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</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>

    <!--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.6</version>
    </dependency>

    <!--Spring-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.12.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.12.RELEASE</version>
    </dependency>

    <!--lombok-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>

    <!--打印mybatis日志-->
    <dependency>
        <groupId>org.bgee.log4jdbc-log4j2</groupId>
        <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
        <version>1.16</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.13</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.13</version>
    </dependency>
</dependencies>
  • POM中进行Maven资源过滤设置,用于找到java文件夹中的配置文件:
<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>
  • 创建相关文件夹(dao、service、controller、pojo)

  • 创建mybatis-config.xml和applicationContext.xml

注意要在项目结构中添加lib文件夹再将所有依赖导入到这个文件夹中,不然之后程序会报错:

整合MyBatis

  • 在resource包中创建数据库配置文件db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=root
  • 在resource包中添加log4j.properties用于输出日志
#OFF,systemOut,logFile,logDailyFile,logRollingFile,logMail,logDB,ALL
log4j.rootLogger=DEBUG,systemOut
log4j.logger.mybatis=DEBUG
#输出到控制台
log4j.appender.systemOut=org.apache.log4j.ConsoleAppender
log4j.appender.systemOut.layout=org.apache.log4j.PatternLayout
log4j.appender.systemOut.layout.ConversionPattern=[%-5p][%-22d{yyyy/MM/dd HH:mm:ssS}][%l]%n%m%n
log4j.appender.systemOut.Threshold=DEBUG
log4j.appender.systemOut.ImmediateFlush=TRUE
log4j.appender.systemOut.Target=System.out
log4j.appender.systemOut.Encoding=UTF-8
  • 在pojo包中新建实体类User.java(这里偷懒用了lombok插件自动生成了属性的相关方法)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    /**
     * 用户ID
     */
    private Integer id;
    
    /**
     * 用户姓名
     */
    private String username;
    
    /**
     * 用户职业
     */
    private String jobs;
    
    /**
     * 联系方式
     */
    private String phone;
}
  • 在dao包中创建接口:UserMapper.java和mybatis映射文件UserMapper.xml,对t_user表进行简单的CRUD

UserMapper.java:

public interface UserMapper {

    /**
     * 增加用户
     *
     * @param user 要增加的用户
     * @return 增加的记录数
     */
    int addUser(User user);

    /**
     * 通过用户ID删除用户
     *
     * @param id 要删除用户ID
     * @return 删除的记录数
     */
    int deleteUserById(Integer id);

    /**
     * 更新用户
     *
     * @param user 要更新的用户
     * @return 更新的记录数
     */
    int updateUser(User user);

    /**
     * 查找所有用户
     *
     * @return 查找的多个用户组成的集合
     */
    List<User> queryAllUser();

    /**
     * 通过用户ID查找用户
     *
     * @param id 用户ID
     * @return 查找到的用户
     */
    User queryUserById(Integer id);

    /**
     * 通过用户名查找用户
     *
     * @param username 用户名
     * @return 查找到的用户组成的集合
     */
    List<User> queryUserByUsername(String username);
}

UserMapper.xml:

<mapper namespace="com.my.dao.UserMapper">
    
    <!--增加一个User-->
    <insert id="addUser" parameterType="com.my.pojo.User">
        insert into t_user(id, username, jobs, phone)
        VALUES (#{id}, #{username}, #{jobs}, #{phone});
    </insert>
    
    <!--更新User-->
    <update id="updateUser" parameterType="com.my.pojo.User">
        update t_user
        set username=#{username},
            jobs=#{jobs},
            phone=#{phone}
        where id = #{id};
    </update>
    
    <!--根据id删除一个User-->
    <delete id="deleteUserById" parameterType="integer">
        delete
        from t_user
        where id = #{id};
    </delete>
    
    <!--查询全部User-->
    <select id="queryAllUser" resultType="com.my.pojo.User">
        select *
        from t_user;
    </select>
    
    <!--根据id查询,返回一个User-->
    <select id="queryUserById" resultType="com.my.pojo.User" parameterType="integer">
        select *
        from t_user
        where id = #{id};
    </select>
    
    <!--根据username查询,返回查询到的User-->
    <select id="queryUserByUsername" resultType="com.my.pojo.User" parameterType="string">
        select *
        from t_user
        <where>
            <if test="username!=null and username!=''">
                username like concat("%", #{username}, "%")
            </if>
        </where>
    </select>
    
</mapper>
  • 配置mybatis-config.xml

1、设置log4J作为日志输出

2、:为 Java 类型设置一个缩写名字。 仅用于 XML 配置,意在降低冗余的全限定类名书写。

当这样配置时,User 可以用在任何使用 com.my.user 的地方

3、配置映射器,这会告诉 MyBatis 去哪里找映射文件(UserMapper.xml)

<configuration>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <typeAliases>
        <package name="com.my.pojo"/>
    </typeAliases>

    <mappers>
        <mapper resource="com/my/dao/UserMapper.xml"/>
    </mappers>
</configuration>
  • 编写UserService.java接口及其实现类UserServiceImpl.xml

UserService.java

public interface UserService {

    /**
     * 增加用户
     *
     * @param user 要增加的用户
     * @return 增加的记录数
     */
    int addUser(User user);

    /**
     * 通过用户ID删除用户
     *
     * @param id 要删除用户ID
     * @return 删除的记录数
     */
    int deleteUserById(Integer id);

    /**
     * 更新用户
     *
     * @param user 要更新的用户
     * @return 更新的记录数
     */
    int updateUser(User user);

    /**
     * 查找所有用户
     *
     * @return 查找的多个用户组成的集合
     */
    List<User> queryAllUser();

    /**
     * 通过用户ID查找用户
     *
     * @param id 用户ID
     * @return 查找到的用户
     */
    User queryUserById(Integer id);

    /**
     * 通过用户名查找用户
     *
     * @param username 用户名
     * @return 查找到的用户组成的集合
     */
    List<User> queryUserByUsername(String username);
}

UserServiceImpl.xml

public class UserServiceImpl implements UserService {

    /**
     * 调用dao层的操作,设置一个set接口,方便Spring容器管理
     */
    private UserMapper userMapper;

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public int deleteUserById(Integer id) {
        return userMapper.deleteUserById(id);
    }

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

    @Override
    public List<User> queryAllUser() {
        return userMapper.queryAllUser();
    }

    @Override
    public User queryUserById(Integer id) {
        return userMapper.queryUserById(id);
    }

    @Override
    public List<User> queryUserByUsername(String username) {
        List<User> users = userMapper.queryUserByUsername(username);
        return users;
    }
}

整合Spring

  • 创建配置文件spring-dao.xml

1.关联数据库文件:context:property-placeholder

2.数据库连接池:bean class="com.mchange.v2.c3p0.ComboPooledDataSource"

3.配置SqlSessionFactory对象:

a)注入数据库连接池

b)配置MyBaties全局配置文件: mybatis-config.xml

4.配置Mapper扫描器(注意,很容易漏!!)

a)给出需要扫描Dao接口包

b)注入sqlSessionFactory

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

    <!-- 配置整合mybatis -->
    <!-- 1.关联数据库文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 2.数据库连接池 -->
    <!--数据库连接池
        dbcp 半自动化操作 不能自动连接
        c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
    -->
    <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
        <!-- 配置连接池属性 -->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!-- 3.配置SqlSessionFactory对象 -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 4.配置Mapper扫描器,扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.my.dao"/>
    </bean>
</beans>
  • 创建配置文件spring-service.xml

1.扫描service相关的bean:context:component-scan

2.UserServiceImpl注入到IOC容器中

3.配置事务管理器:bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager"

<?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.my.service"/>

    <!--2.UserServiceImpl注入到IOC容器中-->
    <bean class="com.my.service.impl.UserServiceImpl" id="userService">
        <property name="userMapper" value="com.my.dao.UserMapper"/>
    </bean>

    <!--3.配置事务管理器 -->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionFactory">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

整合Spring MVC

  • 在resource包中新建springmvc-servlet.xml

  • 编写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">

    <!--DispatcherServlet-->
    <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:applicationContext.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>

    <!--encodingFilter 防止后端乱码-->
    <filter>
        <filter-name>encoding</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</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--设置Session过期时间 15min-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>
  • 编写springmvc-servlet.xml

1.扫描web相关的bean: context:component-scan

2.静态资源默认servlet配置: mvc:default-servlet-handler

3.开启SpringMVC注解驱动: mvc:annotation-driven

4.配置jsp 显示ViewResolver视图解析器: bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"

<?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 
       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 -->
    <!-- 1.扫描web相关的bean -->
    <context:component-scan base-package="com.my.controller"/>

    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <!-- 3.开启SpringMVC注解驱动 -->
    <mvc:annotation-driven/>

    <!-- 4.配置jsp 显示ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>
  • 最后,将所写的配置文件整合到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="classpath:springmvc-servlet.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-dao.xml"/>
</beans>

到此为止,整合工作已经完成,现在开始编写CRUD任务(不考虑前端页面美化)

  • Controller 和 视图层编写

UserController.java

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

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @RequestMapping("/queryAll")
    public String queryAllUser(Model model) {
        List<User> userList = userService.queryAllUser();
        model.addAttribute("userList", userList);
        return "AllUser";
    }

    @RequestMapping("toAdd")
    public String toAdd() {
        return "AddUser";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addUser(User user) {
        userService.addUser(user);
        return "redirect:/user/queryAll";
    }

    @RequestMapping("toUpdate/{id}")
    public String toUpdate(@PathVariable Integer id, Model model) {
        User user = userService.queryUserById(id);
        System.out.println(user);
        model.addAttribute("QUser", user);
        return "UpdateUser";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateUser(User user) {
        userService.updateUser(user);

        return "redirect:/user/queryAll";
    }

    @RequestMapping(value = "/delete/{id}")
    public String deleteUser(@PathVariable Integer id) {
        userService.deleteUserById(id);
        return "redirect:/user/queryAll";
    }

    @RequestMapping(value = "/queryByUsername", method = RequestMethod.POST)
    public String queryByUsername(String username, Model model) {
        List<User> users = userService.queryUserByUsername(username);
        model.addAttribute("userList", users);
        return "AllUser";
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h3><a href="${pageContext.request.contextPath}/user/queryAll">点击进入列表页</a></h3>
  </body>
</html>

AllUser.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</title>
</head>
<body>
<div>
    <form action="${pageContext.request.contextPath}/user/queryByUsername" method="post">
        <label>
            用户名:
            <input type="text" name="username"/>
        </label>
        <input type="submit" value="查询">
    </form>
    <a href="${pageContext.request.contextPath}/user/toAdd">增加</a>
</div>
<div>
    <table>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>工作</th>
            <th>电话</th>
        </tr>

        <c:forEach var="users" items="${requestScope.get('userList')}">
            <tr>
                <td>${users.getId()}</td>
                <td>${users.getUsername()}</td>
                <td>${users.getJobs()}</td>
                <td>${users.getPhone()}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/user/toUpdate/${users.getId()}">修改</a>
                    &nbsp;|&nbsp;
                    <a href="${pageContext.request.contextPath}/user/delete/${users.getId()}">删除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
</div>

</body>
</html>

AddUser.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<div>
    <form action="${pageContext.request.contextPath}/user/add" method="post">
        <table>
            <tr>
                <td>用户名:</td>
                <td><label><input type="text" name="username"></label></td>
            </tr>
            <tr>
                <td>工作:</td>
                <td><label><input type="text" name="jobs"></label></td>
            </tr>
            <tr>
                <td>电话</td>
                <td><label>
                    <input type="text" name="phone"">
                </label></td>
            </tr>
        </table>
        <input type="submit" value="增加">
    </form>
</div>
</body>
</html>

UpdateUser.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<div>
    <form action="${pageContext.request.contextPath}/user/update" method="post">
        <table>
            <tr>
                <td>用户ID:</td>
                <td><label><input type="number" name="id" value="${QUser.id}"></label></td>
            </tr>
            <tr>
                <td>用户名:</td>
                <td><label><input type="text" name="username" value="${QUser.username}"></label></td>
            </tr>
            <tr>
                <td>工作:</td>
                <td><label><input type="text" name="jobs" value="${QUser.jobs}"></label></td>
            </tr>
            <tr>
                <td>电话</td>
                <td><label>
                    <input type="text" name="phone" value="${QUser.phone}">
                </label></td>
            </tr>
        </table>
        <input type="submit" value="修改">
    </form>

</div>
</body>
</html>
  • 项目结构:

  • 运行结果:

完整代码:https://github.com/HuHongSong/SSM

这篇关于整合SSM的demo的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!