SSM整合篇 保姆篇

SSM整合篇



一、创建mavem项目web工程

1、工程是apche下的maven下的webapp

2、指定项目名称和位置
在这里插入图片描述
3、maven的选择。通常是用自己的。默认也行
在这里插入图片描述
4、项目的样子
在这里插入图片描述
5、在mian下面创建Javaresources目录
在这里插入图片描述
在这里插入图片描述
7、完整工程如图:
在这里插入图片描述


二、数据库文件

CREATE TABLE `user` (
  `id` int NOT NULL,
  `username` varchar(10) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;

在这里插入图片描述

三、完整的项目结构

在这里插入图片描述


四、SSM整合

1.1、pom文件


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <!--版本锁定-->
        <spring.version>5.0.2.RELEASE</spring.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <mysql.version>8.0.11</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
    </properties>

    <dependencies>
        <!--aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- aspectj面向切面  aop相关的jar -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>

        <!--context 容器-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--web   springmvc所需要 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring、springmvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--tx 事务-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--jdbc模板技术-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!--mybatis整合spring要用的jar-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!--c3p0数据库连接池-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <!-- servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

        <!--jstl   EL表达式那些要用到-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--log4j日志实现-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <!--slf4j日志门面-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!--slf4j-log4j12桥接器-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!--单元测试-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--junit的单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

    <build>
        <finalName>ssm</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>UTF-8</encoding>
                        <showWarnings>true</showWarnings>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

1.2、配置文件说明

  1. applicationContext.xml
    管理spring和mybatis的文件

  2. springmvc.xml
    管理springmvc的文件

  3. db.properties
    数据库配置文件

  4. web.xml
    web项目核心文件加载applicationContext.xml和springmvc.xml

  5. log4j.properties
    log4j自定义日志文件
    (这算是对之前小编一篇日志框架集成log4f+slf4j的补充) 博文==>JAVA日志框架

1.3、配置文件详解

1.3.1、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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">


    <!-- 使用PropertyOverrideConfigurer后处理器加载数据源参数 -->
    <context:property-override location="classpath:db.properties"/>
    
    <!--事务注解的方式,不采用声明式事务-->
    <!--<tx:annotation-driven transaction-manager="transactionManager" />-->

    <!--方式以:自己指定扫描哪个包-->
    <context:component-scan base-package="sqy.service"></context:component-scan>
    <context:component-scan base-package="sqy.dao"></context:component-scan>
    <context:component-scan base-package="sqy.pojo"></context:component-scan>
    <!--方式二: 开启注解的扫描,只处理spring和mybatis(也就是service和dao)-->
   <!-- <context:component-scan base-package="sqy">
        &lt;!&ndash;排除controller,@Controller注解   spring不扫描&ndash;&gt;
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>-->

    <!--配置连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${dataSource.driverClass}"/>
        <property name="jdbcUrl" value="${dataSource.jdbcUrl}"/>
        <property name="user" value="${dataSource.user}"/>
        <property name="password" value="${dataSource.password}"/>
        <property name="maxIdleTime" value="${dataSource.maxIdleTime}"/>
        <property name="initialPoolSize" value="${dataSource.initialPoolSize}"/>
        <property name="minPoolSize" value="${dataSource.minPoolSize}"/>
        <property name="maxPoolSize" value="${dataSource.maxPoolSize}"/>
    </bean>

    <!--配置SqlSessionFactory工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置Dao接口所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="sqy.dao"/>
    </bean>


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

    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <!--配置AOP增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* sqy.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>

</beans>

1.3.2、springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启SpringMVC注解的支持-->
    <mvc:annotation-driven/>

    <!-- 配置controller扫描包 -->
    <context:component-scan base-package="sqy.controller" />


    <!--配置的视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--过滤静态资源-->
    <mvc:resources location="/css/" mapping="/css/**" />
</beans>

1.3.3、db.properties

dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
dataSource.user=root
dataSource.password=root
dataSource.maxPoolSize=10
dataSource.maxIdleTime=1000
dataSource.minPoolSize=5
dataSource.initialPoolSize=5

1.3.4、web.xml


<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<!--当前web.xml 中web-app 的元素必须按照顺序
  icon?,display-name?,description?,distributable?,context-param*,filter*,
  filter-mapping*,listener*,servlet*,servlet-mapping*,session-config?,
  mime-mapping*,welcome-file-list?,error-page*,taglib*,resource-env-ref*,
  resource-ref*,security-constraint*,login-config?,security-role*,env-entry*,
  ejb-ref*,ejb-local-ref*
-->
<web-app>

    <display-name>Archetype Created Web Application</display-name>

    <!--设置配置文件的路径-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--解决中文乱码的过滤器-->
    <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>

    <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载springmvc.xml配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--启动服务器,创建该servlet-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

1.3.5、log4j.properties(乞丐版)

完整配置看 ==> JAVA日志框架

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

1.4、实体类

User.java

package sqy.pojo;

import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @author suqinyi
 * @Date 2021/9/25
 * user表
 */
@Component
public class User implements Serializable {
    //implements Serializable  实现序列化接口

    private Integer id;
    private String username;
    private String password;

 	//省略get和set和tostring(也可以去集成lombak)
}

1.4、controller

package sqy.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import sqy.pojo.User;
import sqy.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author suqinyi
 * @Date 2021/9/25
 * controller层  用户controller
 */
@Controller
@RequestMapping("/user")
public class UserController {

    //日志
    Logger logger = LoggerFactory.getLogger(getClass());

    //类型注入
    @Autowired
    UserService userService;

    /**
     * 查询所有用户
     */
    @GetMapping("/findAll")
    public String findAllUser(Model model) {
        List<User> users = userService.findAll();
        logger.info("用户{}", users);
        model.addAttribute("userList", users);
        return "list";
    }

    /**
     * 添加用户
     */
    @RequestMapping("/save")
    public void save(User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
        userService.saveUser(user);
        //重定向
        response.sendRedirect(request.getContextPath() + "/user/findAll");
    }

}

1.5、service和impl

UserService.java

package sqy.service;

import sqy.pojo.User;
import java.util.List;

/**
 * @author suqinyi
 * @Date 2021/9/25
 */
public interface UserService {

    //查询所有用户信息
    public List<User> findAll();

    //添加用户
    public void saveUser(User user);
}

UserServiceImpl.java

package sqy.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sqy.dao.UserDao;
import sqy.pojo.User;
import sqy.service.UserService;
import java.util.List;

/**
 * @author suqinyi
 * @Date 2021/9/25
 */
//交给Ioc容器管理
@Service
public class UserServiceImpl implements UserService {

    //注入dao
    @Autowired
    UserDao userDao;

    @Override
    public List<User> findAll() {
        List<User> list = userDao.findAll();
        return list;
    }

    @Override
    public void saveUser(User user) {
        userDao.saveUser(user);
        //测试声明式事务
//        int q=10/0;
    }
}

1.5、dao接口

package sqy.dao;

import org.springframework.stereotype.Repository;
import sqy.pojo.User;
import java.util.List;

/**
 * @author suqinyi
 * @Date 2021/9/25
 * 用户dao接口  sql在resources.sqy.dao下 UserDao.xml
 */

//@Mapper  在配置文件中已经配置了包扫描
@Repository
public interface UserDao {

    //@Select("select * from user")//注解方式个人不推荐
    List<User> findAll();//查询所有用户

    void saveUser(User user);//保存用户
}

1.6、dao对应的xml文件(resources)

注意:包名和层级要保持一致

位置:/resources/sqy/dao/UserDao.xml

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="sqy.dao.UserDao">

	<!--查询所有用户-->
    <select
            id="findAll"
            resultType="sqy.pojo.User">
		select * from user
	</select>

	<!--新增用户-->
    <insert
            id="saveUser"
            parameterType="sqy.pojo.User">
		insert into user values(#{id},#{username},#{password})
	</insert>

</mapper>

1.7、页面文件和文件夹

如图:
在这里插入图片描述
1、创建css文件夹是演示静态资源过滤

2、在WBE-INF安全目录下创建page文件夹和list.jsp演示视图解析器

3、默认加载index.jsp

1.1、index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>默认首页</title>
</head>
<body>

<h1>默认首页</h1>

<form action="/user/save" method="post">
    id:<input type="text" name="id"/><br/>
    用户名:<input type="text" name="username"/><br/>
    密码:<input type="text" name="password"/><br/>
    <input type="submit" value="添加"/><br/>
</form>

</body>
</html>

1.2、list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h3>WEB-INF/pages/list.jsp</h3>

<c:forEach items="${userList}" var="user">
   用户=> ${user.id}  --  ${user.username} --  ${user.password}
</c:forEach>

</body>
</html>

1.8、配置tomcat运行

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1.9、运行效果

在这里插入图片描述
在这里插入图片描述


五、完结

可以看看小编的框架整合系类


下一篇:ssm集成redis详细配置
下下篇:ssm整合mqtt (物联网)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

suqinyi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值