2020-12-07

idea整合Maven+ssm框架(个人学习)

一、搭建整合环境

 

1.整合说明

使用xml+注解的方式整合。

2.整合思路

1.先搭建整合需要的环境

2.先把spring的配置搭建完成

3.使用spring整合springmvc框架

4.spring整合mybatis框架

5.spring整合mybatis框架的事务配置(spring的声明式事务管理)

3.创建数据库表

create database ssm;
use ssm;
create table account (
id int primary key auto_increment,
name varchar(50),
money double
);

4.创建maven工程

使用idea创建maven项目

web依赖service,service依赖dao,dao依赖domain,在ssmdemo的pom.xml文件下引入左标依赖找到对应的<properties>标签,以及

<dependency>标签,cv即可,版本控制在<properties>标签中控制,从坐标依赖中可以看出版本号:spring5.0.2,mysql5.1.6,mybatis3.4.5.

<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.0.2.RELEASE</spring.version>
  <slf4j.version>1.6.6</slf4j.version>
  <log4j.version>1.2.12</log4j.version>
  <mysql.version>5.1.6</mysql.version>
  <mybatis.version>3.4.5</mybatis.version>
</properties>


<dependencies>
  <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>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>compile</scope>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
  </dependency>
  <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>${mybatis.version}</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
  </dependency>
  <dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
    <type>jar</type>
    <scope>compile</scope>
  </dependency>
</dependencies>

5.编写实体类Account,在ssmdemo_domain中编写

快捷键alt+insert快速生成get/set方法和tostring方法。

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

6.编写dao接口

在dao包中编写IAccountDao类

public interface IAccountdao {

       public List<Account> findAll();

       public void saveAccount(Account account);

}

7.编写service接口和实现类

AccountService接口

public interface AccountService { 

        // 查询所有账户 public List<Account> findAll();

       // 保存帐户信息 public void saveAccount(Account account);

}

AccountServiceImpl实现类

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Override
    public List<Account> findAll() {
        System.out.println("Service业务层:查询所有账户...");
        return null;
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("Service业务层:保存帐户...");
    }
}

整合环境搭建完成,如下图,接下来搭建spring的配置

2020-12-07

二、Spring框架代码的编写

搭建和测试spring的开发环境

1.创建resources的资源文件目录管理放置XML配置文件

2.编写applicationContext.xml的配置文件

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

    <!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->
    <context:component-scan base-package="com.igeek" >
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    
</beans>

3.编写test方法测试

创建TestSpring的类

public class TestSpring {
    @Test
    public void test1(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        AccountService as = (AccountService) ac.getBean("accountService");
        as.findAll();
    }
}

结果如下,说明Spring的开发环境搭建成功!

2020-12-07

三、SpringMVC框架代码的编写

搭建和测试SpringMVC的开发环境

1.在web.xml中配置DispatcherServlet前端控制器

 <!--配置前端控制器-->
  <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>

2.在web.xml中配置DispatcherServlet过滤器解决中文乱码

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

3.web.xml中配置的整体效果

  <!--配置前端控制器-->
  <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>

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

4.编写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="com.igeek">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置的视图解析器对象-->
    <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/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
    <!--开启SpringMVC注解的支持-->
    <mvc:annotation-driven/>
</beans>

5.创建jsp页面,并编写contrroller层代码

编写index.jsp代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<a href="account/findAll">测试SpringMVC查询</a>
</body>
</html>

AccountController类

@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("Controller表现层:查询所有账户...");
        return "list";  //在视图解析器中配置了前缀后缀
    }
}

创建list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
</head>
<body>
            <h2>查询所有的账户</h2>
          
</body>
</html>

6.部署Tomcat进行测试

2020-12-07

点击运行测试跳转到 http://localhost:8080/ssmdemo/account/findAll

2020-12-07

到这里,Spring、SpringMVC框架都搭建成功,接下俩开始整合Spring和SpringMVC.

四、Spring整合SpringMVC框架

1.在web.xml中配置ContextLoaderListener监听器

<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
    <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>

2.controller类中注入service对象,调用service对象方法进行测试

@Controller
@RequestMapping("/account)
public class AccountController {

    @Autowired   //按类型注入
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("Controller表现层:查询所有账户...");

        List<Account> list = accountService.findAll();
        return "list";
    }
}

2020-12-07

五、MyBatis框架代码编写

1.在IAccountdao接口方法上添加注解,编写sql语句

@Repository  //此注解代表这是一个持久层,用法类似@controller、@service
public interface IAccountdao {

    @Select("select * from account")
    public List<Account> findAll();

    @Insert("insert into account (name,money) value(#{name},#{money})")
    public void saveAccount(Account account);
}

2.创建SqlMapConfig.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>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments> 
    <!-- 使用的是注解 -->
    <mappers> 
        <!-- <mapper class="com.gx.dao.IAccountdao"/> --> <!-- 该包下所有的dao接口都可以使用 -->
        <package name="com.igeek.dao"/>
    </mappers>
</configuration>

3.创建测试方法

public class TestMyBatis {

    @Test
    public void test01() throws IOException {
        Account account =new Account();
        account.setName("小力");
        account.setMoney(200d);
        // 加载配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 创建SqlSession对象
        SqlSession session = factory.openSession();
        // 获取到代理对象
        IAccountdao dao = session.getMapper(IAccountdao.class);

        // 保存
        dao.saveAccount(account);

        // 提交事务
        session.commit();

        // 关闭资源
        session.close();
        in.close();
    }
    
    @Test
    public void test02() throws Exception {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

        SqlSession session = factory.openSession();

        IAccountdao dao = session.getMapper(IAccountdao.class);

        List<Account> list = dao.findAll();
        for (Account account: list ) {
            System.out.println(account);
        }

        session.close();
        in.close();
    }

  
}

运行结果

2020-12-07

六、Spring整合MyBatis框架

整合目的:吧SqlMapConfig.xml文件整合到applicationContext.xml中

1.在applicationContext.xml中配置数据库连接池

<!--Spring整合MyBatis框架-->
    <!--配置连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>

2.在applicationContext.xml中配置SqlSessionFactory工厂

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

3.在applicationContext.xml中配置IAccountdao接口所在包

因为工厂有了,SqlSession也有了,那代理谁呢,所以我们要配置IAccountdao接口所在包,告诉SqlSession去代理接口所在包中的代理,从而存到IOC容器中

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

上面的操作就是把mybatis中的配置(SqlMapConfig.xml)转移到spring中去,让它产生代理并存到IOC容器中

4.完善Service层代码

在AccountServiceImpl实现类中编写代码:

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private IAccountdao iaccountdao;

    @Override
    public List<Account> findAll() {
        System.out.println("Service业务层:查询所有账户...");
        return iaccountdao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("Service业务层:保存帐户...");
    }
}

5.完善Controller层代码

@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/account/findAll")
    public String findAll(Model model){  //存数据, Model对象
        System.out.println("Controller表现层:查询所有账户...");
        // 调用service的方法
        List<Account> list = accountService.findAll();
        model.addAttribute("list",list);
        return "list";
    }
}

6.完善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>
    <h2>查询所有的账户</h2>
    <c:forEach items="${list}" var="account">
        ${account.name}
    </c:forEach>
</body>
</html>

7.测试

2020-12-07

七、Spring整合Mybatis框架配置事务(Spring的声明式事务管理)

1.在applicationContext.xml中配置Spring框架声明式事务管理

 <!--配置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(* com.igeek.service.Impl.*ServiceImpl.*(..))"/>
    </aop:config>

2.完善index.jsp页面

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

<a href="account/findAll">测试查询</a>

<h3>测试包</h3>

<form action="account/save" method="post">
    姓名:<input type="text" name="name" /><br/>
    金额:<input type="text" name="money" /><br/>
    <input type="submit" value="保存"/><br/>
</form>

</body>
</html>

3.完善Service层、Controller层代码

Service层:在AccountServiceImpl实现类中调用service中的saveAccount(account)方法

 @Override
    public void saveAccount(Account account) {
        System.out.println("Service业务层:保存帐户...");
        iaccountdao.saveAccount(account);  //调用service中的saveAccount(account)方法
    }

Controller层代码:在AccountController类中添加一个保存save的方法

   @RequestMapping("/account/save")
    public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
        accountService.saveAccount(account);
        response.sendRedirect(request.getContextPath()+"/account/findAll");
        return;
    }

4.测试

2020-12-07

2020-12-07

ssm框架整合完成!(简单案例自己学习)

上一篇:Python中正则表达式的使用


下一篇:正则表达式库re