SSM整合

1.导入依赖,这里我是使用JDK1.7,spring的版本时4.2.5

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>www.docin.lzh</groupId>
    <artifactId>db_receipt</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <!-- spring版本号 -->
        <spring.version>4.2.5.RELEASE</spring.version>
    </properties>

    <dependencies>

        <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>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>

        <!-- 添加spring核心依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</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-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>


        <!--邮件-->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <!--工具包-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.6.10</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2.配置applicationContent.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
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="www.docin.lzh"></context:component-scan>

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <!--vonibo_log-->
        <property name="url" value="jdbc:mysql://xxx:3306/vonibo_132?serverTimezone=GMT%2B8"></property>
        <property name="username" value="xxx"></property>
        <property name="password" value="xxx"></property>
    </bean>

    <!--配置Mybatis的SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入连接池数据源配置-->
        <property name="dataSource" ref="dataSource"></property>
        <!--注入mybatis配置信息 注意加上classpath 不然编译出来后是找不到Mybatis-config.xml的文件的-->
        <property name="configLocation" value="classpath:Mybatis-config.xml"></property>
        <!--mapper.xml和mapper.java不在同一个目录 则配置此参数-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>


    <!--扫描Mapper接口并注册为Bean 这个是通过扫描包来配置-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="www.docin.lzh.mapper" />
    </bean>

</beans>

3.配置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:mvc="http://www.springframework.org/schema/mvc"
       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/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">
    <context:component-scan base-package="www.docin.lzh.controller"/>
    <mvc:annotation-driven></mvc:annotation-driven>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <mvc:resources location="/static/" mapping="/static/**" />
</beans>

4.配置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>
        <typeAlias type="www.docin.lzh.pojo.ApplyReceipt" alias="ApplyReceipt"></typeAlias>
    </typeAliases>
</configuration>

5.配置Mapper.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="www.docin.lzh.mapper.ApplyReceiptMapper">
    <select id="getList"  resultType="ApplyReceipt">
        SELECT * FROM apply_receipt WHERE 1 = 1 LIMIT #{startIndex},#{endIndex}
    </select>

    <select id="getCount" resultType="int">
        SELECT count(*) FROM  apply_receipt WHERE 1 = 1
    </select>
</mapper>

6.配置log4j.properties

log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File =D:/db_test/db_receipt/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

7.配置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_3_1.xsd"
         version="3.1">

    <!-- 配置spring提供的监听器,用于启动服务时加载容器。
    该监听器会加载WEB-INF目录中名称为applicationContext.xml的配置文件-->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <!-- 指定spring配置文件的位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <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-MVC.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</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>
            <!--要使用的字符集,一般我们使用UTF-8(保险起见UTF-8最好)-->
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <!--是否强制设置request的编码为encoding,默认false,不建议更改-->
            <param-name>forceRequestEncoding</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <!--是否强制设置response的编码为encoding,建议设置为true,下面有关于这个参数的解释-->
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

8.包结构
在这里插入图片描述
9.Mapper接口

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import www.docin.lzh.pojo.ApplyReceipt;

import java.util.List;

@Mapper
public interface ApplyReceiptMapper {

    public List<ApplyReceipt> getList(@Param("startIndex") int startIndex, @Param("endIndex") int endIndex);

    public int getCount();
}

10.service接口及实现类

import www.docin.lzh.pojo.ApplyReceipt;

import java.util.List;

public interface ApplyReceiptService {

    public List<ApplyReceipt> getList(int startIndex,int endIndex);

    public int getCount();
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import www.docin.lzh.mapper.ApplyReceiptMapper;
import www.docin.lzh.pojo.ApplyReceipt;

import java.util.List;
@Service
public class ApplyReceiptServiceImpl implements ApplyReceiptService {

    @Autowired
    private ApplyReceiptMapper applyReceiptMapper;


    public List<ApplyReceipt> getList(int startIndex, int endIndex) {
        return applyReceiptMapper.getList(startIndex, endIndex);
    }

    @Override
    public int getCount() {
        return applyReceiptMapper.getCount();
    }
}

11.controller

package www.docin.lzh.controller;

import cn.hutool.core.util.StrUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import www.docin.lzh.pojo.ApplyReceipt;
import www.docin.lzh.service.ApplyReceiptService;

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

/**
 * 整合SSM出现的问题:
 *      1.导入依赖之后,需要打开项目结构,找到artifacts,右侧将该项目的所有依赖放到web/WEB-INF/lib目录下,
 *        每次更新依赖需要再次添加,同时该项目要重新部署redeploy,即重新生成war,否则依赖将不生效
 *      2.项目刚刚搭建好,测试的时候,会出现ContextLoaderListener,DispatcherServlet NotFoundClass,
 *        原因是因为依赖没有再lib目录下,可能你再项目结构中看到依赖其实存在,但是打成war包时,war包中的lib目录确实没有该依赖。所以要重新打包
 */
@Controller
public class ApplyReceiptController {

    private static Logger logger = Logger.getLogger(ApplyReceiptController.class);

    @Autowired
    private ApplyReceiptService applyReceiptService;


    /**
     * 初始化首页
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/index")
    public String index(HttpServletRequest request, HttpServletResponse response) {
        int pageNum = 1;
        if (request.getParameter("pageNum") != null) pageNum = Integer.parseInt(request.getParameter("pageNum"));
        logger.warn("request pageNum:"+pageNum);
        int pageSize = 5;
        int count = applyReceiptService.getCount();
        List<ApplyReceipt> list = applyReceiptService.getList((pageNum - 1) * pageSize, pageSize);
        request.setAttribute("applyReceiptList", list);
        request.setAttribute("pageNum", pageNum == 0 ? 1 : pageNum);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPage",(count % 5 == 0 ? count / 5 : (count / 5) + 1));
        logger.warn("list size:" + list.size() + ",pageNum:" + pageNum + "pageSize: " + pageSize + ", totalPage:"+ (count % 10 == 0 ? count / 10 : (count / 10) + 1));
        return "index";
    }

}

12.web/WEB-INF/jsp/index.jsp

<%@ page import="www.docin.lzh.pojo.ApplyReceipt" %>
<%@ page import="java.util.List" %>
<%@ page import="cn.hutool.core.util.StrUtil" %>
<%@ page import="org.apache.log4j.Logger" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/2/9
  Time: 9:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>首页</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
          crossorigin="anonymous">
    <!-- 在线引入 jQuery JavaScript文件 -->
     
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
    <%!
        private static Logger logger = Logger.getLogger("index.jsp");
    %>
    <%
        List<ApplyReceipt> applyReceiptList = (List<ApplyReceipt>) request.getAttribute("applyReceiptList");
        int pageNum = Integer.parseInt(request.getAttribute("pageNum") + "");
        int pageSize = Integer.parseInt(request.getAttribute("pageSize") + "");
        int totalPage = Integer.parseInt(request.getAttribute("totalPage") + "");
        logger.warn("pageNum:" + pageNum + ",pageSize:" + pageSize + ",totalPage:" + totalPage);
    %>
</head>
<body>
<div class=".container-fluid">
    <div class="row">
        <div class="col-md-2"></div>
        <div class="col-md-8">
            <table class="table table-bordered">
                <thead>
                <tr>
                    <td>id</td>
                    <td>email</td>
                    <td>taxpayer_id</td>
                    <td>balance</td>
                    <td>user_id</td>
                    <td>phone</td>
                </tr>
                </thead>
                <tbody>
                <%
                    if (applyReceiptList != null && applyReceiptList.size() > 0) {
                        for (ApplyReceipt applyReceipt : applyReceiptList) {
                %>
                <tr class="<%=applyReceipt.getId() % 2 == 0 ? "info" : ""%>">
                    <td><%=applyReceipt.getId()%>
                    </td>
                    <td><%=applyReceipt.getEmail()%>
                    </td>
                    <td><%=applyReceipt.getTaxpayer_id()%>
                    </td>
                    <td><%=applyReceipt.getBalance()%>
                    </td>
                    <td><%=applyReceipt.getUser_id()%>
                    </td>
                    <td><%=applyReceipt.getPhone()%>
                    </td>
                </tr>
                <%
                        }
                    }
                %>
                </tbody>
            </table>
        </div>
        <div class="col-md-2"></div>
    </div>
    <div class="row">
        <div class="col-md-2"></div>
        <div class="col-md-8">
            <ul class="pagination center">
                <%
                    if (pageNum > 1) {
                %>
                <li>
                    <a  href="/index?pageNum=<%=pageNum - 1%>" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <%
                    }
                %>
                <%
                    if (totalPage > 1) {
                        for (int i = 0; i < totalPage; i++) {
                %>
                <li class="<%=pageNum == (i + 1) ? "active" : ""%>"><a href="/index?pageNum=<%=i+1%>"><%=i + 1%>
                </a></li>
                <%
                        }
                    }
                %>
                <%
                    if (pageNum < totalPage) {
                %>
                <li>
                    <a href="/index?pageNum=<%=pageNum + 1%>" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
                <%
                    }
                %>

            </ul>
        </div>
        <div class="col-md-2"></div>

    </div>
</div>
</body>
</html>

13.启动测试
13.1问题,在上面的controller中也提到了,必须将依赖打包放到WEB-INF/lib目录下。idea中找到Project Structure----Artifacts----右侧Output Layout,找到当前项目,如果WEB-INF下没有lib目录,自己创建
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值