用idea整合ssm详细教程(Spring+SpringMVC+Mybatis)图文,也可以下载我整合好的

整个过程的说明:整合的大致思路是,用Spring框架整合其他框架,在Spring的配置文件中整合Mybatis,开启注解扫描service注解,配置SqlSessionFactory工厂,配置Mapper接口包,配置事务通知;在SpringMVC的配置文件中开启注解扫描处理Controller注解,配置视图解析器,过滤静态资源,开启SpringMVC注解支持。大概就是这样,建议跟我创建的文件夹来,开整--------

 

一.打开idea,新建Maven项目

      点击“Maven”,选择“Create from archetype”,选择webapp(注意有两个webapp,选第二个,不要选错),然后点击next

 

GroupId和ArtifactId随便写,点击next

 

为了加快所需要包下载的速度点击加号,在弹出的Name和value中分别加入archetypeCatalog和internal然后点击OK,点击next

点击finish

二.添加依赖

打开pom.xml文件,为以后修改版本号,我把版本号放在properties中

然后在dependencies加入依赖,可以直接复制我的dependencies到你的工程中(只覆盖dependencies本部分就可以了)

<dependencies>
<!--spring-->
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.6.8</version>
      </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</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-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-test</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>
      <!--spring end-->

      <!--junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
      <!--junit end-->

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

      <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标签-->
      <dependency>
          <groupId>jstl</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
      </dependency>
      <!--jstl end-->

      <!-- 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-->

      <!--mybatis-->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
      </dependency>

      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.0</version>
      </dependency>
      <!--mybatis end-->

      <dependency>
          <groupId>c3p0</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.1.2</version>
          <type>jar</type>
          <scope>compile</scope>
      </dependency>

      <!--实现mybatis分页的插件,pagehelper-->
      <dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper</artifactId>
          <version>5.1.2</version>
      </dependency>
      <!--pagehelper end-->




  </dependencies>

三.创建所需的目录

 

右键java目录,设置java目录为Sources Root

同理,右键resourses目录,设置它为Resources Root

在Java目录下创建cn.incom(可以随意起)目录,然后在cn.incom目录下分别创建controller目录(存放controller),domain(持久层)目录,mapper(存放mapper接口)目录,service(服务层)目录;service目录下再创建Impl(服务实现)目录,效果如图:

 

在resources目录下创建mapper目录,存放mapper文件

在webapp目录下创建css(存放css文件)、js(存放文件)、images(存放图片资源)目录;在WEB-INF下创建pages目录(存放jsp文件),如下图:

 

四.开始编写xml整合框架

 1.创建applicationContext.xml,右键resources创建xml选择“Spring Config”

名字(可以随意起,一般为)为applicationContext

 

由于他给的约束(画红线的地方)是不够的的,你可以直接复制我的代码,连接池的数据部分根据自己的数据库端口号,账号,密码自行填写

 

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

    <!--开启注解扫描。希望处理service-->
    <context:component-scan base-package="cn.incom.service"/>

    <!--Springz整合Mybatis框架,start-->
      <!--配置连接池,Driver,端口号,数据库名,账号,密码根据自己的数据库而定-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3333/db_mybatis"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--Spring整合Mybatis框架,end-->

    <!--配置SqlSessionFactory工厂,start-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--配置扫描pojo-->
        <property name="typeAliasesPackage" value="cn.incom.domain"/>
        <!--扫描resources目录下mapper目录中的xml文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <!--分页插件的使用-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行一个-->
                        <value>
                            offsetAsPageNum=false
                            rowBoundsWithCount=false
                            pageSizeZero=true
                            reasonable=false
                            rowBoundsWithCount=false
                            supportMethodsArguments=false
                            returnPageInfo=none
                        </value>
                    </property>
                </bean>
            </array>
        </property>


    </bean>

    <!--配置Mapper接口包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.incom.mapper"/>
    </bean>

    <!--p配置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(* cn.incom.service.Impl.*.*(..))"/>
    </aop:config>

</beans>
<!--结束-->

 

 

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

    <!--开启注解扫描,只扫描Controller-->
    <context:component-scan base-package="cn.incom.controller"/>

    <!--配置视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
           <!--设置前缀-->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <!--设置后缀-->
        <property name="suffix" value=".jsp"/>
        <!--这样做的目的是,比如当我们在返回welcome.jsp页面时不用返回一长串的"/WEB-INF/pages/welcome.jsp",而只用写"welcome"就可以了-->
    </bean>

    <!--过滤静态资源,图片啊,css,js之类的-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>

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

<!--结束-->

3.创建日志文件log4j.properties

右击resources,创建file

直接输入log4j.properties

 

log4j.properties的内容可以直接复制我的如下:

 

# 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

4.配置web.xml

  可以把我的代码直接复制到你的web-app的约束下

<display-name>Archetype Created Web Application</display-name>
  <!--配置Spring的监听器-->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--加载配置文件-->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--配置前端控制器,开始没映射会出现红线,没关系-->
  <servlet>
      <servlet-name>dispatcherServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!--SpringMVC配置文件-->
      <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>

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

到此,整合完了,开始验证了

 

五.验证(查询我的数据库中t_user表中的所有用户,在页面中显示出来)

  1.在domain包中建立持久类User,数据类型与数据库中的类型对应

package cn.incom.domain;

public class User {
    private Integer id;
    private String username;
    private String jobs;
    private String phone;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getJobs() {
        return jobs;
    }

    public void setJobs(String jobs) {
        this.jobs = jobs;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", jobs='" + jobs + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}

 

 

2.在resources目录中mapper目录建立mapper文件为了好区分,我的mapper文件名字为:UserMapper.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="cn.incom.mapper.UserMapper">
    <select id="findAll" resultType="cn.incom.domain.User">

        SELECT * FROM t_user
    </select>

</mapper>

**注意namespace的路径是mapper接口的路径,在application.xml中我设置的mapper接口路径是cn.incom文件夹下的mapper目录

 

3.在cn.incom文件夹mapper下建立mapper接口,为了区分名字为UserMapper,方法名字跟mapper文件中的定义的名字一样,例如我的UserMapper.xml中查询全部用户的id为findAll,那么方法名就为findAll,注入注解@Repository,如图:

 

package cn.incom.mapper;

import cn.incom.domain.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper {
    List<User> findAll();
}

 

 

4.在service目录中建立对应的服务接口,接口的方法跟cn.incom.mapper中UserMapper接口 的方法一样,

 

5.编写接口的实现类,在service目录Impl目录建立服务的接口实现类

package cn.incom.service.Impl;

import cn.incom.domain.User;
import cn.incom.mapper.UserMapper;
import cn.incom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    public List<User> findAll() {
        return userMapper.findAll();
    }
}

 

6.建立controller

package cn.incom.controller;

import cn.incom.domain.User;
import cn.incom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    public UserService userService;

    @RequestMapping("/toAll")
    public String toAll(Model model){
        List<User> userList=userService.findAll();
        model.addAttribute("userlist",userList);
        return "success";//返回success.jsp页面
    }
}

 

7.在webapp根目录下建立index.jsp;在WEB-INF/pages目录下建立success.jsp

 

index.jsp的内容:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="user/toAll">点击查看</a>
</body>
</html>

 

成功页面success,jsp的内容,注意引入jstl标签库

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

关闭忽略el表达式:

isELIgnored="false

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: HP
  Date: 2020/4/3
  Time: 23:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<c:forEach items="${userlist}" var="userlist">
   <td>${userlist.id}</td>
    <td>${userlist.username}</td>
    <td>${userlist.jobs}</td>
    <td>${userlist.phone}</td>
</c:forEach>

</body>
</html>

 

.部署到Tomcat上

1.添加运行环境

2.点击“+”好添加

 

完成,运行项目

完成,success页面有点偷懒,不过没事

 

如果整合不好的可以留言,也可以下载我的源码https://pan.baidu.com/s/11w7DZiWTUZOS0SWXlstSvA      提取码:tnmo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值