214、SpringMVC学习笔记(八)【SSM框架整合】2019.09.20
作者:互联网
0、目录
Spring5 + SpringMVC5 + MyBatis3.5
若需要整合三个框架,则需要将每个步骤具体划分,保证每个框架都能够运行,以防止出现未知错误
1、项目创建
- 创建maven的web项目
- 替换web.xml为3.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
- jar包依赖
<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>
- 在src/mian/resources中新增applicationContext.xml配置文件,并配置context属性扫描package
<?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
- 导入mvc依赖jar
<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>
- web.xml中配置springmvc核心控制器、字符编码、REST提交过滤器
<!--最前面添加过滤器-->
<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>
- 新建springmvc.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: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引入到applicationContext.xml中
<!--引入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>
- 配置springmvc.xml的关键配置信息
<!--配置视图解析器-->
<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>
- 静态资源路径配置
- 在webapp目录下加入view和static文件夹
- 在springmvc.xml中加入静态资源放行
<!--静态资源放行-->
<mvc:resources mapping="/static/**" location="/static/"/>
- 重新部署启动服务,检测静态界面能否访问,访问成功则可进行下一步的整合
4、集成MyBatis
- 导入mybatis所需jar包
<!--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.properties
# 主要配置
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
-
applicationContext.xml集成jdbc.properties
- 新建jdbc.properties
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
- xml集成
<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>
- SqlSessionFactoryBean配置
<!--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、测试代码编写
- 新建com.hliedu.ssm.domain.Emp类
public class Emp {
private Integer eid;
private String ename;
private String job;
//setter getter ...
}
- 新建com.hliedu.ssm.mapper.EmpMapper类
@Repository
public interface EmpMapper {
List<Emp> queryEmp();
}
- 新建com.hliedu.ssm.service.EmpService接口
public interface EmpService {
List<Emp> queryEmp();
}
- 新建com.hliedu.ssm.service.impl.EmpServiceImpl类实现EmpService接口
@Service("empService")
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpMapper empMapper;
@Override
public List<Emp> queryEmp() {
return empMapper.queryEmp();
}
}
- 在src/main/resources下新建com/hliedu/ssm/mapper多层次的目录,该目录中的文件最终要和对应的Mapper接口编译到同一个目录下,否则将出现Invalid bound statement (not found)错误
<?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>
-
在src/test/java下新建com.hliedu.test.SSMTest类
-
main方法测试
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());
}
}
- Junit测试(需导入junit依赖和spring-test依赖)
<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、添加事务支持
- 加入spring-tx依赖jar包
<!--声明式事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
- 加入tx声明约束
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
- applicationContext.xml中加入声明式事务
<!-- 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"/>
- 在需要开启事务的类或方法中加入@Transcation注解
@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;
}
- validation参数校验,加入验证jar包
<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>
-
给属性加入验证注解
-
给handler中方法入参加入@Valid注解
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):
- 如果上述操作都未解决该异常,检查文件路径
- 出现C3P0连接池问题
om.mchange.v2.c3p0.impl.NewProxyResultSet.isClosed
出现该错误,请对照上面c3p0依赖部分的版本是否为com.mchange下的0.9.5.2
8、参考链接
标签:2019.09,xml,214,spring,springframework,SSM,version,org,public 来源: https://blog.csdn.net/youyouwuxin1234/article/details/101066486