1、预备知识及工具。
- 掌握java语言基础知识。
- 了解基本的MySQL相关知识。
- 了解http协议。
- 了解Jdbc技术。
- 了解maven项目管理工具。
2、 开发环境
- 操作系统:macOS 10.13.4
- IDE:IntelliJ IDEA
- JDK版本:jdk1.7
- Web服务器:tomcat 8.5.242
- 版本控制工具:git 2.15.1
- 项目管理工具:maven 3.5.2
- 数据库:mysql 14.14
开发环境配置可以按照上面的顺序在网上搜索相应的安装配置教程。
3、搭建过程
3.1 框架搭建前,先在MySQL创建我们需要查询的数据库。
-
打开数据库,并连接到数据中。
- 新建一个名为demo的数据库。
CREATE DATABASE demo DEFAULT CHARACTER SET utf8;
- 在demo数据库下,新建名为t_user数据表。
CREATE TABLE t_user (
id BIGINT NOT NULL,
name VARCHAR(50) COMMENT '姓名',
age INTEGER COMMENT '年龄'
);
-
给t_user表中插入测试数据。
3.2 使用idea新建maven项目,并对项目运行环境进行配置。
3.3 建立maven项目的目录结构,并在maven的pom.xml配置文件中添加项目所需要的依赖包。(注意:尽量和我的pom.xml保持一样,避免因为版本问题,出现错误)
-
完整pom.xml文件在下面文件给出,可复制。
3.4 编写demo项目类文件。
类文件分为三层:
- dao即Data Access Object,数据访问对象。
- controller,控制层,用来接收http请求。
-
service,业务逻辑层,用来处理与业务相关的逻辑。
-
完整项目结构如下图。
- 配置文件及类文件如下,文件中注释对配置进行了说明。
- 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>site.wzhe.spring</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>4.3.16.RELEASE</spring.version>
<mysql-connector-java.version>5.1.17</mysql-connector-java.version>
<mybatis.version>3.4.4</mybatis.version>
<mybatis-spring.version>1.3.1</mybatis-spring.version>
<c3p0.version>0.9.1.2</c3p0.version>
<jackson.version>2.9.5</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</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-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<finalName>demo</finalName>
</build>
</project>
- .gitignore
# Maven #
target/
# IDEA #
.idea/
*.iml
# Eclipse #
.settings/
.metadata/
.classpath
.project
Servers/
- web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- 加载Spring容器配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring容器加载所有bean的配置文件的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/applicationContext.xml</param-value>
</context-param>
<!-- 配置SpringMVC核心控制器,将所有的请求(除了刚刚Spring MVC中的静态资源请求)都交给Spring MVC -->
<!-- DispatcherServlet上下文在初始化的时候会建立自己的IoC上下文,用以持有spring mvc相关的bean。 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/applicationContext-mvc.xml</param-value>
</init-param>
<!--用来标记是否在项目启动时就加在此Servlet,0或正数表示容器在应用启动时就加载这个Servlet,
当是一个负数时或者没有指定时,则指示容器在该servlet被选择时才加载.正数值越小启动优先值越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--为DispatcherServlet建立映射-->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!-- 拦截所有请求,千万注意是(/)而不是(/*) -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 设置编码过滤器 -->
<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>
</web-app>
- jdbc.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
jdbc.initialPoolSize=20
jdbc.maxPoolSize=100
jdbc.minPoolSize=10
jdbc.maxIdleTime=600
jdbc.acquireIncrement=5
jdbc.maxStatements=50
jdbc.idleConnectionTestPeriod=60
- UserDaoMapper.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="site.wzhe.spring.demo.dao.UserDao">
<select id="getById" parameterType="java.lang.Long" resultType="User">
SELECT id, username, age
FROM t_user
WHERE id = #{id, jdbcType=BIGINT}
</select>
</mapper>
- mybatis-config.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--实体类匹配成XXXMapper.xml中可以直接使用的类型,相当于一个别名,在XXXMapper.xml中就无需再写完整的实体类全路径,直接用alias的值来代替-->
<configuration>
<typeAliases>
<typeAlias type="site.wzhe.spring.demo.entity.UserEntity" alias="User" />
</typeAliases>
</configuration>
- applicationContext.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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- ===============spring容器(父容器)的配置文件 ================== -->
<context:component-scan base-package="site.wzhe.spring.demo.service"/>
<!-- 加载jdbc.properties配置文件 -->
<context:property-placeholder location="classpath:jdbc/jdbc.properties"/>
<!--数据源-链接数据库的基本信息-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
<!--扫描 XXXDaoMapper.xml映射文件,配置扫描的路径-->
<property name="mapperLocations" value="classpath:mappers/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找之中的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="site.wzhe.spring.demo.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!--事务管理-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource" />
</bean>
<!--开启事务注解扫描-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
- applicationContext-mvc.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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- ===============spring web容器(子容器)的配置文件 ================== -->
<!-- org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,
它会像一个检查员,对进入DispatcherServlet的URL进行筛查,如果发现是静态资源的请求,
就将该请求转由Web应用服务器默认的Servlet处理,如果不是静态资源的请求,才由DispatcherServlet继续处理。 -->
<mvc:default-servlet-handler/>
<!-- 告知Spring,会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。-->
<!--SpringMVC相关如下配置,经过验证,这个是SpringMVC必须要配置的,因为它声明了@RequestMapping、@RequestBody、@ResponseBody等。并且,该配置默认加载很多的参数绑定方法,比如json转换解析器等。-->
<mvc:annotation-driven>
<!-- json请求无法通过@RequestBody转为对象,添加这个就可以解决-->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 指定要扫描的包的位置 -->
<context:component-scan base-package="site.wzhe.spring.demo.controller" />
<!-- 对静态资源文件的访问,因为Spring MVC会拦截所有请求,导致jsp页面中对js和CSS的引用也被拦截,配置后可以把对资源的请求交给项目的默认servlet而不是Spring MVC-->
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
<!-- 为RequestMappingHandlerAdapter装配可处理JSON格式的请求/响应消息的HttpMessage Converter-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" p:messageConverters-ref="messageConverters"/>
<util:list id="messageConverters">
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</util:list>
<!-- 配置Spring MVC的视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 有时我们需要访问JSP页面,可理解为在控制器controller的返回值加前缀和后缀,变成一个可用的URL地址 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- UserController.java 文件
package site.wzhe.spring.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import site.wzhe.spring.demo.entity.UserEntity;
import site.wzhe.spring.demo.service.UserService;
/**
* @author: andup.
* @description:
* @date: 2018/7/21.
*/
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/api/user/{id}", method = RequestMethod.GET)
@ResponseBody
UserEntity getById(@PathVariable Long id) {
return userService.getById(id);
}
}
- UserDao.java文件
package site.wzhe.spring.demo.dao;
import site.wzhe.spring.demo.entity.UserEntity;
/**
* @author: andup.
* @description:
* @date: 2018/7/21.
*/
public interface UserDao {
UserEntity getById(Long id);
}
- UserEntity.java文件
package site.wzhe.spring.demo.entity;
/**
* @author: andup.
* @description:
* @date: 2018/7/21.
*/
public class UserEntity {
private Long id;
private String userName;
private Integer age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
- UserService.java文件
package site.wzhe.spring.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.wzhe.spring.demo.dao.UserDao;
import site.wzhe.spring.demo.entity.UserEntity;
/**
* @author: andup.
* @description:
* @date: 2018/7/21.
*/
@Service
public class UserService {
@Autowired
private UserDao userDao;
public UserEntity getById(Long id) {
return userDao.getById(id);
}
}
-
后面四个类文件对应项目中类位置如下。
3.5 通过游览器输入地址,测试项目是否运行成功。
-
在游览器地址栏输入:localhost:8080/api/user/1
- 后端返回数据。目前大多数项目都是前后端分离项目,后端返回数据,前端进行渲染,展示给用户。所以,游览器从后端返回Json格式的数据即可。
如果对你有帮助,可以关注我,后续有更多详细教程。
原创文章,请勿用于商业用途,转载请注明出处。
up