Spring和SpringMVC的整合是无缝整合。而MyBatis是第三方。

原始方式整合

1、创建数据表

这里创建了一个account表,里面有id、name、money字段。

2、创建maven工程

3、导入坐标

spring-context、aspectj、spring-tx【事务相关】、spring-test【测试相关】、spring-webmvc、servlet-api、jsp-api;
mybatis、mybatis-spring【mybatis整合spring时使用】、mysql-connetcor-java、c3p0;
junit、jstl

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.2.8.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-tx</artifactId>
  10. <version>5.2.8.RELEASE</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework</groupId>
  14. <artifactId>spring-test</artifactId>
  15. <version>5.2.8.RELEASE</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework</groupId>
  19. <artifactId>spring-webmvc</artifactId>
  20. <version>5.2.8.RELEASE</version>
  21. </dependency>
  22. <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
  23. <dependency>
  24. <groupId>org.aspectj</groupId>
  25. <artifactId>aspectjweaver</artifactId>
  26. <version>1.9.6</version>
  27. <scope>runtime</scope>
  28. </dependency>
  29. <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
  30. <dependency>
  31. <groupId>javax.servlet</groupId>
  32. <artifactId>javax.servlet-api</artifactId>
  33. <version>4.0.1</version>
  34. <scope>provided</scope>
  35. </dependency>
  36. <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
  37. <dependency>
  38. <groupId>javax.servlet.jsp</groupId>
  39. <artifactId>javax.servlet.jsp-api</artifactId>
  40. <version>2.3.3</version>
  41. <scope>provided</scope>
  42. </dependency>
  43. <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  44. <dependency>
  45. <groupId>mysql</groupId>
  46. <artifactId>mysql-connector-java</artifactId>
  47. <version>5.1.49</version>
  48. </dependency>
  49. <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
  50. <dependency>
  51. <groupId>com.mchange</groupId>
  52. <artifactId>c3p0</artifactId>
  53. <version>0.9.5.5</version>
  54. </dependency>
  55. <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
  56. <dependency>
  57. <groupId>org.mybatis</groupId>
  58. <artifactId>mybatis</artifactId>
  59. <version>3.5.5</version>
  60. </dependency>
  61. <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
  62. <dependency>
  63. <groupId>org.mybatis</groupId>
  64. <artifactId>mybatis-spring</artifactId>
  65. <version>2.0.5</version>
  66. </dependency>
  67. <!-- https://mvnrepository.com/artifact/junit/junit -->
  68. <dependency>
  69. <groupId>junit</groupId>
  70. <artifactId>junit</artifactId>
  71. <version>4.13</version>
  72. <scope>test</scope>
  73. </dependency>
  74. <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
  75. <dependency>
  76. <groupId>javax.servlet</groupId>
  77. <artifactId>jstl</artifactId>
  78. <version>1.2</version>
  79. </dependency>
  80. </dependencies>

4、编写实体类

Account.java

  1. package com.learn.domain;
  2. public class Account {
  3. private Integer id;
  4. private String name;
  5. private Double money;
  6. public Integer getId() {
  7. return id;
  8. }
  9. public void setId(Integer id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public Double getMoney() {
  19. return money;
  20. }
  21. public void setMoney(Double money) {
  22. this.money = money;
  23. }
  24. }

5、编写Mapper接口

AccountMapper.java

  1. package com.learn.mapper;
  2. import com.learn.domain.Account;
  3. import java.util.List;
  4. public interface AccountMapper {
  5. public void save(Account account);
  6. public List<Account> findAll();
  7. }

6、编写Service接口

AccountService.java

  1. package com.learn.service;
  2. import com.learn.domain.Account;
  3. import java.util.List;
  4. public interface AccountService {
  5. public void save(Account account);
  6. public List<Account> findAll();
  7. }

7、编写Service接口实现

AccountServiceImpl.java

  1. package com.learn.service.impl;
  2. import com.learn.domain.Account;
  3. import com.learn.mapper.AccountMapper;
  4. import com.learn.service.AccountService;
  5. import org.apache.ibatis.io.Resources;
  6. import org.apache.ibatis.session.SqlSession;
  7. import org.apache.ibatis.session.SqlSessionFactory;
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  9. import org.springframework.stereotype.Service;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. import java.util.List;
  13. @Service("accountService")
  14. public class AccountServiceImpl implements AccountService {
  15. public void save(Account account) {
  16. try {
  17. InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapperConfig.xml");
  18. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  19. SqlSession sqlSession = sqlSessionFactory.openSession();
  20. AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
  21. mapper.save(account);
  22. sqlSession.commit();
  23. sqlSession.close();
  24. }catch (IOException e){
  25. e.printStackTrace();
  26. }
  27. }
  28. public List<Account> findAll() {
  29. //没问题返回List,有问题返回null
  30. try {
  31. InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapperConfig.xml");
  32. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  33. SqlSession sqlSession = sqlSessionFactory.openSession();
  34. AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
  35. List<Account> accountList = mapper.findAll();
  36. sqlSession.close();
  37. return accountList;
  38. }catch (IOException e){
  39. e.printStackTrace();
  40. }
  41. return null;
  42. }
  43. }

8、编写Controller

AccountController.java

  1. package com.learn.controller;
  2. import com.learn.domain.Account;
  3. import com.learn.service.AccountService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import org.springframework.web.servlet.ModelAndView;
  9. import java.util.List;
  10. @Controller
  11. @RequestMapping("/account")
  12. public class AccountController {
  13. //注入service对象
  14. @Autowired
  15. private AccountService accountService;
  16. //设置响应数据的编码格式.即保存成功可以正常显示,而不是???
  17. @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
  18. @ResponseBody
  19. //保存,这里实际上应该跳转到某个页面,这里先不那么设置
  20. public String save(Account account){
  21. accountService.save(account);
  22. return "保存成功";
  23. }
  24. //查询
  25. @RequestMapping("/findAll")
  26. public ModelAndView findAll(){
  27. List<Account> accountList = accountService.findAll();
  28. ModelAndView modelAndView = new ModelAndView();
  29. modelAndView.addObject("accountList",accountList);
  30. modelAndView.setViewName("accountList");
  31. return modelAndView;
  32. }
  33. }

9、编写表单添加页面

save.jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>Title</title>
  5. </head>
  6. <body>
  7. <h1>添加账户信息表单</h1>
  8. <form name="accountForm" action="${pageContext.request.contextPath}/account/save" method="post">
  9. 账户名称:<input type="text" name="name"><br>
  10. 账户金额:<input type="text" name="money"><br>
  11. <input type="submit" value="保存"><br>
  12. </form>
  13. </body>
  14. </html>

10、编写列表展示页面

accountList.jsp,这里需要使用到el表达式

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  3. <html>
  4. <head>
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <h1>展示账户数据列表</h1>
  9. <table>
  10. <tr>
  11. <th>账户id</th>
  12. <th>账户名称</th>
  13. <th>账户金额</th>
  14. </tr>
  15. <c:forEach items="${accountList}" var="account">
  16. <tr>
  17. <td>${account.id}</td>
  18. <td>${account.name}</td>
  19. <td>${account.money}</td>
  20. </tr>
  21. </c:forEach>
  22. </table>
  23. </body>
  24. </html>

11、配置文件

Spring配置文件

applicationContext.xml
这个配置文件只管理service和mapper,不管理controller,需要exclude一下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:aop="http://www.springframework.org/schema/aop"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/tx
  12. http://www.springframework.org/schema/tx/spring-tx.xsd
  13. http://www.springframework.org/schema/aop
  14. http://www.springframework.org/schema/aop/spring-aop.xsd">
  15. <!--组件扫描 扫描service和mapper-->
  16. <context:component-scan base-package="com.learn">
  17. <!--需要排除controller扫描,这个需要交给springmvc-->
  18. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  19. </context:component-scan>
  20. </beans>

SpringMVC配置文件

spring-mvc.xml
配置组件扫描【主要扫描controller】、配置mvc注解驱动、配置内部资源视图解析器、开放静态资源【因为如果pattern是*,但是有些静态资源无法解析,需要放行】

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  12. <!--组件扫描 主要扫描controller-->
  13. <context:component-scan base-package="com.learn.controller">
  14. </context:component-scan>
  15. <!--配置mvc注解驱动-->
  16. <mvc:annotation-driven></mvc:annotation-driven>
  17. <!--配置内部资源视图解析器-->
  18. <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  19. <property name="prefix" value="/WEB-INF/pages"/>
  20. <property name="suffix" value=".jsp"/>
  21. </bean>
  22. <!--开放静态资源访问权限-->
  23. <mvc:default-servlet-handler/>
  24. </beans>

Mybatis映射文件

AccountMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.learn.mapper.AccountMapper">
  4. <insert id="save" parameterType="account">
  5. insert into account values (#{name},#{money});
  6. </insert>
  7. <select id="findAll" resultType="account">
  8. select * from account;
  9. </select>
  10. </mapper>

MyBatis核心文件

SqlMapperConfig.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <configuration>
  4. <properties resource="jdbc.properties"></properties>
  5. <!--定义别名-->
  6. <typeAliases>
  7. <!--<typeAlias type="com.learn.domain.Account" alias="account"></typeAlias>-->
  8. <!--也可以使用扫包的方式,别名默认是实体名称或者实体名称的首字母小写-->
  9. <package name="com.learn.domain"/>
  10. </typeAliases>
  11. <environments default="development">
  12. <environment id="development">
  13. <transactionManager type="JDBC"></transactionManager>
  14. <dataSource type="POOLED">
  15. <property name="driver" value="${jdbc.driver}"/>
  16. <property name="url" value="${jdbc.url}"/>
  17. <property name="username" value="${jdbc.username"/>
  18. <property name="password" value="${jdbc.password}"/>
  19. </dataSource>
  20. </environment>
  21. </environments>
  22. <mappers>
  23. <package name="com.learn.mapper"/>
  24. </mappers>
  25. </configuration>

数据库连接信息文件

jdbc.properties

Web.xml文件

web.xml

idea默认是2.3的,可以升个级

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="3.0"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  6. </web-app>

在web.xml文件中,需要配置spring监听器、springmvc前端控制器和乱码过滤器。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="3.0"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  6. <!--配置spring监听器-->
  7. <context-param>
  8. <param-name>contextConfigLocation</param-name>
  9. <param-value>classpath:applicationContext.xml</param-value>
  10. </context-param>
  11. <listener>
  12. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  13. </listener>
  14. <!--springmvc前端控制器-->
  15. <servlet>
  16. <servlet-name>DispatcherServlet</servlet-name>
  17. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  18. <init-param>
  19. <param-name>contextConfigLocation</param-name>
  20. <param-value>classpath:spring-mvc.xml</param-value>
  21. </init-param>
  22. <load-on-startup>1</load-on-startup>
  23. </servlet>
  24. <servlet-mapping>
  25. <servlet-name>DispatcherServlet</servlet-name>
  26. <url-pattern>/</url-pattern>
  27. </servlet-mapping>
  28. <!--乱码过滤器-->
  29. <filter>
  30. <filter-name>CharacterEncodingFilter</filter-name>
  31. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  32. <init-param>
  33. <param-name>encoding</param-name>
  34. <param-value>UTF-8</param-value>
  35. </init-param>
  36. </filter>
  37. <filter-mapping>
  38. <filter-name>CharacterEncodingFilter</filter-name>
  39. <url-pattern>/*</url-pattern>
  40. </filter-mapping>
  41. </web-app>

日志文件

log4j.xml或者log4j.properties

  1. ### direct log messages to stdout ###
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  3. log4j.appender.stdout.Target=System.out
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  6. ### direct messages to file mylog.log ###
  7. log4j.appender.file=org.apache.log4j.FileAppender
  8. log4j.appender.file.File=c:\mylog.log
  9. log4j.appender.file.layout=org.apache.log4j.PatternLayout
  10. log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  11. ### set log levels - for more verbose logging change 'info' to 'debug' ###
  12. log4j.rootLogger=debug, stdout

12、测试

实际上这里有个问题,就是在保存中文的时候,显示的都是???,不知道是什么原因,是不是web.xml没有配置正确导致的。