SSM整合——环境搭建
环境搭建1、功能点分页数据校验jquery 前端校验 + JSR303 后端校验ajaxRest 风格的 URI;使用 HTTP 协议请求方式的动词,来表示对资源的操作(GET:查询,POST:新增,PUT:修改,DELETE:删除)2、技术点基础框架——SSM(SpringMVC + Spring + MyBatis)数据库——MySQL前端框架——bootstrap 快速搭建简洁美观的界面项目
环境搭建
文章目录
1、功能点
-
分页
-
数据校验
jquery 前端校验 + JSR303 后端校验
-
ajax
-
Rest 风格的 URI;使用 HTTP 协议请求方式的动词,来表示对资源的操作(GET:查询,POST:新增,PUT:修改,DELETE:删除)
2、技术点
- 基础框架——SSM(SpringMVC + Spring + MyBatis)
- 数据库——MySQL
- 前端框架——bootstrap 快速搭建简洁美观的界面
- 项目依赖管理——Maven
- 分页——pagehelper
- 逆向工程——MyBatis Generator
3、基础环境
3.1、创建一个 maven 项目
3.2、引入项目的依赖的 jar 包
- spring
- springmvc
- mybatis
- 数据库连接池,驱动包
- 其他
<dependencies>
<!--引入项目依赖包-->
<!--SpringMVC、Spring-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.16</version>
</dependency>
<!--Spring-JDBC-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.16</version>
</dependency>
<!--Spring面向切面-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.16</version>
</dependency>
<!--MyBatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!--MyBatis整合Spring的适配包-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!--数据库连接池、驱动-->
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--jstl\servlet-api\junit-->
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
3.3、引入 bootstrap 前端框架
<%--引入jquery--%>
<script type="text/javascript" src="static/js/jquery-3.5.1.min.js"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
<script src="static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
3.4、编写 SSM 整合的关键配置文件
web.xml,spring,springMVC,MyBatis,使用 MyBatis 的逆向工程生成对应的 bean 和 mapper
a > web.xml(配置 servlet、监听器和过滤器)
-
启动 Spring 的容器(是一个监听器:ConfigurableWebApplicationContext)
服务器一启动,加载 Spring 配置文件的位置
-
springMVC 的前端控制器(是一个 servlet)
springMVC 请求响应流程 -
字符编码过滤器(是一个过滤器)
字节编码过滤器 CharacterEncodingFilter -
HiddenHttpMethodFilter(是一个过滤器)
HiddenHttpMethodFilter
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--1、启动Spring的容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ConfigurableWebApplicationContext</listener-class>
</listener>
<!--2、springMVC的前端控制器,拦截所有请求-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:dispatcherServlet-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--3、字符编码过滤器,一定要放在所有过滤器之前-->
<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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--4、使用Rest风格的URI:将页面普通的post请求转为指定的delete或者put请求-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
b > springMVC 的配置文件:dispatcherServlet-servlet.xml(与网站有关的,控制器组件)
- 扫描组件(但是这个是 springMVC 的配置文件,所有只需要扫描 Controller 即可)
- 视图解析器
- 将 springMVC 不能处理的请求交给 servlet
- 能支持 springMVC 更高级的一些功能:JSR303 校验,快捷的 ajax…映射动态请求
<!--SpringMVC的配置文件,包含网站跳转逻辑的控制、配置-->
<!--扫描组件-->
<context:component-scan base-package="crud" use-default-filters="false">
<!--只扫描控制器-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置视图解析器:方便页面返回-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--两个标准配置-->
<!--将springMVC不能处理的请求交给servlet-->
<mvc:default-servlet-handler/>
<!--能支持springMVC更高级的一些功能:JSR303校验,快捷的ajax...映射动态请求-->
<mvc:annotation-driven/>
c > spring 的配置文件:applicationContext.xml(数据源,事务控制,和 MyBatis 的整合)
- 扫描组件,但是不扫控制器(springMVC 已经扫描了)
- 数据源
- 配置和 MyBatis 的整合
- sqlSessionFactory(属性中需要指定数据源、 mybatis 全局配置文件的位置和 mapper 文件的位置)
spring 配置文件 sqlSessionFactory - MapperScannerConfigurer(配置扫描器,将 mybatis 接口的实现(是一个代理对象)加入到 ioc 容器中)
- sqlSessionFactory(属性中需要指定数据源、 mybatis 全局配置文件的位置和 mapper 文件的位置)
- 事务控制(DataSourceTransactionManager)
<!--扫描组件,但是不扫控制器-->
<context:component-scan base-package="crud">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--Spring的配置文件,这里主要配置和业务逻辑有关的-->
<!--数据源,事务控制,xxx-->
<context:property-placeholder location="classpath:dbconfig.properties"></context:property-placeholder>
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--=======================配置和MyBatis的整合=======================-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--指定mybatis全局配置文件的位置-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="dataSource" ref="pooledDataSource"></property>
<!--指定mybatis,mapper文件的位置-->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<!--配置扫描器,将mybatis接口的实现(是一个代理对象)加入到ioc容器中-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描所有的dao接口的实现,加入到ioc容器中-->
<property name="basePackage" value="crud.dao"></property>
</bean>
<!--====================================================================-->
<!--=======================事务控制=======================-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--控制住数据源-->
<property name="dataSource" ref="pooledDataSource"></property>
</bean>
<!--开启基于注解的事务,使用xml配置形式的事务(必要、主要的都是使用配置式)-->
<aop:config>
<!--切入点表达式-->
<aop:pointcut id="txPoint" expression="execution(* crud.service..*(..))"/>
<!--配置事务增强器-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
<!--配置事务增强:事务如何切入-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--所有方法都是事务方法-->
<tx:method name="*"/>
<!--以get开始的所有方法-->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--=====================================================================-->
<!--Spring配置文件的核心点:数据源、与mybatis的整合、事务控制-->
d > MyBatis 的配置文件:mybatis-config.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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="crud.bean"/>
</typeAliases>
</configuration>
使用 MyBatis 的逆向工程生成对应的 bean 和 mapper:
创建 mbg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!--注释的配置-->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接信息-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.1.11:3306/ssm_crud"
userId="root"
password="Opfordream@0518">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--指定javaBean生成的位置-->
<javaModelGenerator targetPackage="crud.bean" targetProject="./src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--指定sql映射文件指定的位置-->
<sqlMapGenerator targetPackage="mapper" targetProject="./src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--指定dao接口生成的位置:mapper接口生成的位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="crud.dao" targetProject="./src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!--指定每个表的生成策略-->
<table tableName="tbl_emp" domainObjectName="Employee"></table>
<table tableName="tbl_dept" domainObjectName="Department"></table>
</context>
</generatorConfiguration>
@Test
public void test() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("./src/main/resources/mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
3.5、修改 mapper 文件
在 EmployeeMapper.java
接口文件中定义两个查询带部门的方法:
List<Employee> selectByExampleWithDept(EmployeeExample example);
Employee selectByPrimaryKeyWithDept(Integer empId);
同时在 Employee.java
类中加入 Department 的成员变量,生成其对应的 get 和 set 方法:
//希望查询员工的同时,部门信息也显示出来
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
在 EmployeeMapper.xml
中定义 sql:
<resultMap id="WithDeptResultMap" type="crud.bean.Employee">
<id column="emp_id" jdbcType="INTEGER" property="empId" />
<result column="emp_name" jdbcType="VARCHAR" property="empName" />
<result column="gender" jdbcType="CHAR" property="gender" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="d_id" jdbcType="INTEGER" property="dId" />
<!--指定联合查询出的部门字段的封装-->
<association property="department" javaType="crud.bean.Department">
<id column="dept_id" property="id"></id>
<result column="dept_name" property="deptName"></result>
</association>
</resultMap>
<!--查询员工时不带部门的-->
<select id="selectByExample" parameterType="crud.bean.EmployeeExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from tbl_emp
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from tbl_emp
where emp_id = #{empId,jdbcType=INTEGER}
</select>
<sql id="WithDept_Column_List">
e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id, d.dept_name
</sql>
<!--查询员工时带部门的-->
<!--List<Employee> selectByExampleWithDept(EmployeeExample example);-->
<select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="WithDept_Column_List" />
from tbl_emp e
left join tbl_dept d
on e.d_id = d.dept_id
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<!--Employee selectByPrimaryKeyWithDept(Integer empId);-->
<select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
select
<include refid="WithDept_Column_List" />
from tbl_emp e
left join tbl_dept d
on e.d_id = d.dept_id
where emp_id = #{empId,jdbcType=INTEGER}
</select>
3.6、搭建 Spring 单元测试环境
导入 Spring 单元测试的包:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.16</version>
<scope>test</scope>
</dependency>
测试代码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentMapper;
/**
* 测试Department的Mapper
* 推荐Spring的项目就可以使用Sring的单元测试,可以自动注入需要的组件
* 1、导入SpringTest模块
* 2、@ContextConfiguration指定Spring配置文件的位置
* 3、直接autowired即可
*/
@org.junit.Test
public void testCRUD(){
/*//1、创建SpringIOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//2、从容器中拿mapper
DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);*/
System.out.println(departmentMapper);
}
}
org.apache.ibatis.binding.MapperProxy@64f555e7
如果出现问题:
可以把 Spring 配置文件中,注释掉
<property name="mapperLocations" value="classpath:mapper/*.xml">
事后一定要重新开启,不然也会报错。
给 Department 类生成有参和无参构造器,然后添加几个部门;测试 EmployeeMapper,给 Employee 类生成有参和无参构造器,添加批量几个员工:
<!--配置一个可以执行批量的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
<constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
@Autowired
SqlSession sqlSession;
/**
* 测试Department的Mapper
* 推荐Spring的项目就可以使用Sring的单元测试,可以自动注入需要的组件
* 1、导入SpringTest模块
* 2、@ContextConfiguration指定Spring配置文件的位置
* 3、直接autowired即可
*/
@org.junit.Test
public void testCRUDDept(){
/*//1、创建SpringIOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//2、从容器中拿mapper
DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);*/
System.out.println(departmentMapper);
//1、插入几个部门
departmentMapper.insertSelective(new Department(null, "开发部"));
departmentMapper.insertSelective(new Department(null, "测试部"));
}
@Test
public void testCRUDEmp(){
//2、生成员工数据,测试员工插入
employeeMapper.insertSelective(new Employee(null, "Jerry", "M", "Jerry@li.com",1));
//2、批量插入多名员工:可以使用执行批量操作的sqlSession
/*for(){
employeeMapper.insertSelective(new Employee(null, "Jerry", "M", "Jerry@li.com",1));
}*/
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
for (int i = 0; i < 1000; i++) {
String uid = UUID.randomUUID().toString().substring(0, 5) + i;
mapper.insertSelective(new Employee(null, uid, "M", uid+"@li.com", 1));
}
}
}
更多推荐
所有评论(0)