其他分享
首页 > 其他分享> > 214、SpringMVC学习笔记(八)【SSM框架整合】2019.09.20

214、SpringMVC学习笔记(八)【SSM框架整合】2019.09.20

作者:互联网

0、目录


Spring5 + SpringMVC5 + MyBatis3.5
若需要整合三个框架,则需要将每个步骤具体划分,保证每个框架都能够运行,以防止出现未知错误

1、项目创建

<?xml version="1.0" encoding="UTF-8"?>
<web-app  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns="http://xmlns.jcp.org/xml/ns/javaee"
          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
          id="WebApp_ID" version="3.1">
  <display-name>ssm</display-name>
</web-app>

2、集成Spring

 <properties>
        <spring.version>5.1.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--Spring官方依赖包 start-->
        <!-- bean context core expression -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--Spring对JDBC的支持-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring测试jar,用于Junit单元测试-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--spring aop官方包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--其他厂商aop支持依赖包-->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
        <!--Spring官方依赖包 end-->
    </dependencies>
<?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="com.hliedu"/>
</beans>

3、集成SpringMVC

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

        <!--文件上传依赖的jar包-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
 <!--最前面添加过滤器-->
  <filter>
    <filter-name>encodingFilter</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--SpringMVC是基于Servlet的-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <!--SpringMVC的核心控制器,中央控制器-->
    <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>

    <!--大于0 ,表示启动服务器加载-->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!--Struts2 是基于拦截器 filter-->

  <!--配置映射-->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <!--映射根路径,所有的请求,包括静态资源都走 dispatcherServlet-->
    <!--/* 一般是指拦截所有的请求,/是指跟目录映射-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--发送PUT和DELETE请求需要配置的过滤器-->
  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <servlet-name>dispatcherServlet</servlet-name>
  </filter-mapping>
<?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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

</beans>
 <!--引入springmvc.xml-->
    <import resource="springmvc.xml"/>

注意:此时applicationContext.xml文件为核心配置,springmvc.xml为mvc配置,将来会有更多的类似于mvc这样的附属配置被加入到核心配置中。

所以需要修改web.xml中contextConfigLocation属性为applicationContext.xml

 <!--默认加载 applicationContext.xml-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:applicationContext.xml</param-value>
    </init-param>
 <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置视图前缀-->
        <property name="prefix" value="/view/"/>
        <!--配置视图解析后缀,目前的视图采用JSP-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--注解驱动-->
    <mvc:annotation-driven/>

    <!--注意:文件上传的配置,必须配置ID,而且ID的值固定为:multipartResolver-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--最大的上传大小,字节 ,如果设置为-1的话,就表示无限制-->
        <property name="maxUploadSize" value="102400"/>
        <!--文件编码-->
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
 <!--静态资源放行-->
    <mvc:resources mapping="/static/**" location="/static/"/>

4、集成MyBatis

 <!--mybatis所需jar包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>
        <!--注意该jar包为com.mchange下的0.9.5.2版本-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <!--逆向工程所需包-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>

        <!--日志所需包-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- Spring集成MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
# 主要配置
log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO
jdbc.username=test
jdbc.password=123456
# mysql8 加入时区
jdbc.url=jdbc:mysql://localhost:3306/jdbcdb?serverTimezone=UTC
# 采用新版的cj驱动
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.maxActive=50
<context:property-placeholder location="classpath:jdbc.properties"/>
 <!-- C3P0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
<!--sqlSessionFactory配置-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--注册映射文件-->
    <property name="mapperLocations" value="classpath*:com/hliedu/ssm/mapper/*Mapper.xml"/>
    <!--配置别名, 扫描实体类包,不支持ant通配符风格,必须配置到位-->
    <property name="typeAliasesPackage">
        <value>
            com.hliedu.ssm.domain
            <!--可换行配置多个-->
        </value>
    </property>
</bean>

<!--MyBatis中Mapper接口的扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--配置mapper接口所在的包-->
    <property name="basePackage" value="com.hliedu.**.mapper"/>
</bean>

5、测试代码编写

public class Emp {
    private Integer eid;
    private String ename;
    private String job;
    //setter getter ...
}
@Repository
public interface EmpMapper {

    List<Emp> queryEmp();
}
public interface EmpService {

    List<Emp> queryEmp();
}
@Service("empService")
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Emp> queryEmp() {
        return empMapper.queryEmp();
    }
}
<?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">
<!--注意namespace所指定的接口-->
<mapper namespace="com.hliedu.ssm.mapper.EmpMapper">

    <!--注意statement配置与接口中的方法描述一致-->
    <select id="queryEmp"  resultType="com.hliedu.ssm.domain.Emp">
        select * from emp
      </select>
</mapper>

在这里插入图片描述

public class SSMTest {
    public static void main(String[] args) {
        ApplicationContext context = new 
                ClassPathXmlApplicationContext("applicationContext.xml");
        EmpService empService = (EmpService)context.getBean("empService");
        System.out.println(empService.queryEmp());
    }
}
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext.xml"})
public class SSMTest {

    @Autowired
    ApplicationContext ctx;

    @Test
    public void test() {
        EmpService empService = (EmpService)ctx.getBean("empService");
        System.out.println(empService.queryEmp());
    }
}

6、添加事务支持

 <!--声明式事务-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
xmlns:tx="http://www.springframework.org/schema/tx"

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
<!-- 1 事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 2 事务交予spring管理,transaction-manager 配置事务管理器-->
<tx:annotation-driven transaction-manager="txManager"/>
    @Transactional
    @Override
    public boolean addEmp() {
        Emp emp1 = new Emp(1005 , "zs" , "程序员");
        empMapper.addEmp(emp1);

        //可能会出现异常的行
        System.out.println(10/0);

        Emp emp2 = new Emp(1006 , "ls" , "项目经理");
        empMapper.addEmp(emp2);
        return false;
    }
  <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.13.Final</version>
        </dependency>

7、Controller加入

@RequestMapping("/emp")
@Controller
public class EmpController {
    @Autowired
    private EmpService empService;

    @RequestMapping("query")
    public String query(ModelMap modelMap){
        List<Emp> emps = empService.queryEmp();
        modelMap.addAttribute("emps" , emps);
        return "empList";
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Emp</title>
</head>
<body>

    ${requestScope.emps}
</body>
</html>

(1)出现查询时无法调用mapper.xml问题Invalid bound statement (not found):

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

om.mchange.v2.c3p0.impl.NewProxyResultSet.isClosed
出现该错误,请对照上面c3p0依赖部分的版本是否为com.mchange下的0.9.5.2

8、参考链接

【01】SSM框架整合

标签:2019.09,xml,214,spring,springframework,SSM,version,org,public
来源: https://blog.csdn.net/youyouwuxin1234/article/details/101066486