就是我们通常的SSM整合。
先创建一个web的Maven项目。
在项目的pom.xml文件中添加如下:
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.4.RELEASEversion>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.10.3version>
dependency>
在resources目录下创建spring-mvc.xml文件,并在其中添加如下:
<context:component-scan base-package="com.ara.controller"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true" >
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
bean>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
博主这里习惯将所有的控制器Controller存放在com.ara.controller
包下。
在web/WEB-INF下出web.xml中添加如下:
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
在我们指定存放Controller的包下(博主这里是com.ara.controller
)创建一个HelloController类,其内容如下:
package com.ara.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@RequestMapping("/hello")
@ResponseBody
public String hello(){
System.out.println("hello SpringMvc 你好");
return "hello SpringMvc 你好";
}
}
当出现上面情况,说明我们的SpringMvc的环境就已经搭建成功了。
Spring和SpringMvc本就是一家,说实话,整合起来。。。可能说不上整合吧,哈哈。
我们还是编写一个关于业务层的Spring配置文件spring-service.xml,内容如下:
<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
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.ara.service"/>
beans>
这个配置文件就专门来存放管理service层的对象。
然后我们编写一个总配置文件application.xml来将两个配置文件联合在一起:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
beans>
上述配置文件都存放在resources目录下。
现在我们所需要处理的就是怎么让项目启动时,加载application.xml文件,这也很简单,更改web.xml的加载文件即可。
编写service层,在com.ara.service下创建测试HelloService接口:
package com.ara.service;
public interface HelloService {
String hello();
}
在com.ara.service.impl编写HelloService的实现类HelloServiceImpl:
package com.ara.service.impl;
import com.ara.service.HelloService;
import org.springframework.stereotype.Service;
@Service
public class HelloServiceImpl implements HelloService {
public String hello() {
System.out.println("hello Service 你好");
return "hello Service!";
}
}
然后修改HelloController如下:
package com.ara.controller;
import com.ara.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@Autowired
private HelloService helloService;
@RequestMapping("/hello")
@ResponseBody
public String hello(){
System.out.println("hello SpringMvc 你好");
return helloService.hello();
}
}
到此,Spring整合SpringMvc就算是成功了。
数据库数据准备如下:
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE `user`(
`id` INT PRIMARY KEY AUTO_INCREMENT COMMENT '主键id',
`name` VARCHAR(30) NOT NULL COMMENT '用户名',
`password` VARCHAR(30) NOT NULL COMMENT '密码'
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO USER(`name`,`password`) VALUES('Ara_Hu','123456'),('张三','123456'),('李思','123456'),('王武','123456'),('赵柳','123456'),('田七','123456');
创建对应实体类,实体类存放在com.ara.pojo包下:
package com.ara.pojo;
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
在pom.xml中导入依赖如下:
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.4version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
dependency>
这里需要在pom.xml添加如下:
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
防止后面编写的XXXMapper.xml不能正常导出。
在resources目录下创建Mybatis的配置文件mybatis-config.xml,其内容如下:
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<typeAliases>
<package name="com.ara.pojo" />
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.ara.mapper"/>
mappers>
configuration>
这里将dao层的内容放置在com.ara.mapper包下。
先创建UserMapper接口:
package com.ara.mapper;
import com.ara.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUsers();
}
再编写其对应的Mapper.xml文件,其内容如下:
<mapper namespace="com.ara.mapper.UserMapper">
<select id="getUsers" resultType="User">
select * from user;
select>
mapper>
编写Mybatis的工具类MybatisUtils:
package com.ara.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
//SqlSessionFactory对象
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//加载Mybatis配置文件
InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");
//通过SqlSessionFactoryBuilder构建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
} catch (IOException e) {
e.printStackTrace();
}
}
//返回SqlSession的方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
在com.ara.test包下创建测试类:
package com.ara.test;
import com.ara.mapper.UserMapper;
import com.ara.pojo.User;
import com.ara.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MybatisTest {
@Test
public void test(){
//获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//通过sqlSession获取对应Mapper对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
//遍历循环输出
for (User user : users) {
System.out.println(user);
}
//关闭sqlSession对象
sqlSession.close();
}
}
此时,Mybatis环境搭建成功。
对于Spring,我们知道它的核心之一就是IOC容器,我们使用Spring整合Mybatis,就是想办法将Mybatis的对象注入到Spring的IOC容器中即可。
在pom.xml中添加如下:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.4version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.4.RELEASEversion>
dependency>
在resources目录下编写数据库连接的配置文件db.properties,其内容如下:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
在resources目录下创建spring-dao.xml,其内容如下:
<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
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.ara.mapper"/>
bean>
beans>
这里,我们使用Spring管理了数据源、SqlSessionFactory对象和扫描包,之前Mybatis的配置文件就“压缩”如下:
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<typeAliases>
<package name="com.ara.pojo" />
typeAliases>
configuration>
我们的测试类和Mybatis的工具类都可以直接舍弃了。
在application.xml中引入spring-dao.xml文件,如下:
在service层中编写UserService接口:
package com.ara.service;
import com.ara.pojo.User;
import java.util.List;
public interface UserService {
List<User> getUsers();
}
编写其实现类UserServiceImpl:
package com.ara.service.impl;
import com.ara.mapper.UserMapper;
import com.ara.pojo.User;
import com.ara.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public List<User> getUsers() {
return userMapper.getUsers();
}
}
在controller层中编写UserController:
package com.ara.controller;
import com.ara.pojo.User;
import com.ara.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUsers")
@ResponseBody
public List<User> getUsers(){
return userService.getUsers();
}
}
到此,三个框架整合就成功了。
关于Java的学习,博主这里推荐一个优秀的Java讲师 狂神说,哔哩哔哩搜索狂神说,就可以查看狂神老师的所有Java教学视频,真的非常优秀。