速览
- 使用Spring+Spring MVC+MyBatis搭建项目
- 开发工具IDEA(Ecplise步骤类似,代码完全一样)
- 项目类型Maven工程
- 数据库MySQL8.0
- 数据库连接池:Druid
发现不合适的出门左转,不要浪费时间~~
数据库信息如下:
- 数据库名:webtest
- 测试表名称user
CREATE TABLE `user` (
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`tel` varchar(11) NOT NULL,
`email` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
步骤
Step 1:创建Maven工程
- 新建Project,选择Maven,选择jdk,选择创建模板为webapp(注意看清名称)
2.填写项目信息,然后一路next,最后finish
Step 2:添加依赖和插件,修改pom.xml文件,主要信息如下:
- Spring相关依赖
- MyBatis相关依赖
- MySQL连接相关依赖
- Druid连接池
- 测试依赖
- FastJSON依赖
- Tomcat插件
- Maven插件
- 资源拷贝插件(为了避免部分开发工具中不拷贝java包下的资源文件,不是所有人都会遇到这个问题,可以不配,具体请看这里)
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo</groupId>
<artifactId>ssmdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!--定义版本号-->
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<junit.version>4.9</junit.version>
<fastjson.version>1.2.28</fastjson.version>
<mybatis.version>3.2.8</mybatis.version>
<mybatis.spring.version>1.2.2</mybatis.spring.version>
<mysql.version>8.0.11</mysql.version>
<druid.version>1.0.9</druid.version>
</properties>
<!--依赖-->
<dependencies>
<!--Spring相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!--fastJson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!--Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--MyBatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--MyBatis与Spring整合的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!-- MySql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
</dependencies>
<build>
<!-- 自定义资源文件拷贝行为 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<!--使用的插件-->
<plugins>
<!--上面的资源文件拷贝的插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!--tomcat插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 3:修改web.xml 文件(webapp/WEB-INF下),完成内容如下(所有的配置文件稍后会列出):
- 初始化Spring容器
<!--初始化spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--读取spring文件夹下所有applicationContext-打头的文件-->
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
- 创建监听器,监听项目启动的时候初始化我们的Spring容器
<!--监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
- 创建一个Fliter,解决POST请求中文乱码问题(在pom.xml配置Tomcat插件是指定的UTF-8只能解决GET请求的乱码问题)
<!-- 解决post乱码 -->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 创建DispatcherServlet(我们可以使用SpringMVC的基础)
<!-- springmvc的前端控制器 -->
<servlet>
<servlet-name>ssmdemo-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ssmdemo-servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 完整的web.xml
<!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 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<!--初始化spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<!--监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 解决post乱码 -->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- springmvc的前端控制器 -->
<servlet>
<servlet-name>ssmdemo-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ssmdemo-servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Step 4:在java下创建需要package(没有java请创建),方便稍后写配置文件
- controller包
- service包
- mapper包
- domain包
Step 5:在resources(没有请创建)包下创建spring包,用来存放Spring相关的配置文件,创建springmvc.xml配置文件
- 开启controller的扫描
- 开启mvc的注解扫描
- 配置转换器
<?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">
<!--开启controller扫描 指定扫描的基础包-->
<context:component-scan base-package="com.demo.controller"/>
<!--开启注解扫描-->
<mvc:annotation-driven>
<!--指定转换器为fastjson-->
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
Step 6:继续在spring文件下创建applicationContext-service.xml配置文件,配置service层的相关配置
- 开启组件扫描
<?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.demo.service"/>
</beans>
Step 7:继续在spring文件夹下创建applicationContext-dao.xml配置文件,配置持久层相关配置
- 在resources下创建properties文件夹,新建db.properties配置文件,配置连接数据库相关属性
db.properties文件内容如下:
数据库连接驱动、url、用户名、密码
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/webtest?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
jdbc.username=root
jdbc.password=root
- 在spring文件夹下创建applicationContext-dao.xml配置文件
- 配置数据源
- 配置sqlsession工厂(SqlMapConfig.xml稍后创建)
- 配置mapper代理
applicationContext-dao.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"
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">
<!--读取db.properties配置文件内容-->
<context:property-placeholder location="classpath:properties/db.properties"/>
<!--配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="maxActive" value="10" />
<property name="minIdle" value="5" />
</bean>
<!--配置sqlsession工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
</bean>
<!--配置mapper代理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.demo.mapper"/>
</bean>
</beans>
Step 8:在resources文件夹下创建mybatis文件夹,存放mybatis相关配置,
创建SqlMapConfig.xml文件
SqlMapConfig.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>
<!--配置pojo的别名-->
<typeAliases>
<package name="com.demo.domain"/>
</typeAliases>
</configuration>
至此,resources文件夹下的内容配置完成,回到java文件夹下
Step 9:在com.demo.domain下创建User实体类
User.java
package com.demo.domain;
import java.io.Serializable;
/**
* @author 11699
* @date 20/3/27 - 16:53
*/
public class User implements Serializable {
private String username;
private String password;
private String tel;
private String email;
private String name;
//省略getter和setter方法
}
Step 10:在mapper文件下创建接口UserMapper,同时创建同名的UserMapper.xml文件,写一个简单的查询全部的方法
UserMapper接口
package com.demo.mapper;
import com.demo.domain.User;
import java.util.List;
/**
* @author 11699
* @date 20/3/27 - 16:57
*/
public interface UserMapper {
List<User> findAll();
}
UserMapper.xml文件
<?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" >
<!--指定命名空间-->
<mapper namespace="com.demo.mapper.UserMapper">
<!--查询全部 id必须与接口的方法名对应-->
<select id="findAll" resultType="com.demo.domain.User">
select * from user
</select>
</mapper>
Step 11:service下创建接口UserService,同时创建impl包,在impl包下创建UserServiceImpl类,扩展UserService接口
在接口中定义个查询全部的方法,并在实现类中实现此方法
UserService接口
package com.demo.service;
import com.demo.domain.User;
import java.util.List;
/**
* @author 11699
* @date 20/3/27 - 17:07
*/
public interface UserService {
/**
* 查找全部User
* @return User
*/
List<User> findAll();
}
UserServiceImpl实现类(不要忘记@Service注解)
package com.demo.service.impl;
import com.demo.domain.User;
import com.demo.mapper.UserMapper;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author 11699
* @date 20/3/27 - 17:08
*/
//别忘了service注解哦
@Service
public class UserServiceImpl implements UserService {
//注入UserMapper对象
@Autowired
private UserMapper mapper;
@Override
public List<User> findAll() {
return mapper.findAll();
}
}
Step 12:在controller下创建UserController类
package com.demo.controller;
import com.demo.domain.User;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author 11699
* @date 20/3/27 - 17:12
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/all")
public List<User> findAll(){
return userService.findAll();
}
}
运行测试配置
启动没有报错的话就可以在浏览器中测试访问:
http://localhost:8080/user/all
成功返回JSON串
项目完整结构
├─.idea
│ ├─codeStyles
│ ├─dictionaries
│ └─inspectionProfiles
├─src
│ └─main
│ ├─java
│ │ └─com
│ │ └─demo
│ │ ├─controller
│ │ ├─domain
│ │ ├─mapper
│ │ └─service
│ │ └─impl
│ ├─resources
│ │ ├─mybatis
│ │ ├─properties
│ │ └─spring
│ └─webapp
│ └─WEB-INF
└─target
├─apache-tomcat-maven-plugin
├─classes
│ ├─com
│ │ └─demo
│ │ ├─controller
│ │ ├─domain
│ │ ├─mapper
│ │ └─service
│ │ └─impl
│ ├─mybatis
│ ├─properties
│ └─spring
├─generated-sources
│ └─annotations
├─maven-status
│ └─maven-compiler-plugin
│ └─compile
│ └─default-compile
└─tomcat
├─conf
├─logs
├─webapps
└─work
└─Tomcat
└─localhost
└─_
源码下载
点击这里下载源码