1槽片、預(yù)備知識(shí)及工具何缓。
- 掌握java語言基礎(chǔ)知識(shí)。
- 了解基本的MySQL相關(guān)知識(shí)还栓。
- 了解http協(xié)議碌廓。
- 了解Jdbc技術(shù)。
- 了解maven項(xiàng)目管理工具蝙云。
2氓皱、 開發(fā)環(huán)境
- 操作系統(tǒng):macOS 10.13.4
- IDE:IntelliJ IDEA
- JDK版本:jdk1.7
- Web服務(wù)器:tomcat 8.5.242
- 版本控制工具:git 2.15.1
- 項(xiàng)目管理工具:maven 3.5.2
- 數(shù)據(jù)庫:mysql 14.14
開發(fā)環(huán)境配置可以按照上面的順序在網(wǎng)上搜索相應(yīng)的安裝配置教程。
3勃刨、搭建過程
3.1 框架搭建前波材,先在MySQL創(chuàng)建我們需要查詢的數(shù)據(jù)庫。
-
打開數(shù)據(jù)庫身隐,并連接到數(shù)據(jù)中廷区。
- 新建一個(gè)名為demo的數(shù)據(jù)庫。
CREATE DATABASE demo DEFAULT CHARACTER SET utf8;
- 在demo數(shù)據(jù)庫下贾铝,新建名為t_user數(shù)據(jù)表隙轻。
CREATE TABLE t_user (
id BIGINT NOT NULL,
name VARCHAR(50) COMMENT '姓名',
age INTEGER COMMENT '年齡'
);
-
給t_user表中插入測(cè)試數(shù)據(jù)。
3.2 使用idea新建maven項(xiàng)目垢揩,并對(duì)項(xiàng)目運(yùn)行環(huán)境進(jìn)行配置玖绿。
3.3 建立maven項(xiàng)目的目錄結(jié)構(gòu),并在maven的pom.xml配置文件中添加項(xiàng)目所需要的依賴包叁巨。(注意:盡量和我的pom.xml保持一樣斑匪,避免因?yàn)榘姹締栴},出現(xiàn)錯(cuò)誤)
-
完整pom.xml文件在下面文件給出锋勺,可復(fù)制蚀瘸。
3.4 編寫demo項(xiàng)目類文件狡蝶。
類文件分為三層:
- dao即Data Access Object,數(shù)據(jù)訪問對(duì)象贮勃。
- controller贪惹,控制層,用來接收http請(qǐng)求寂嘉。
-
service奏瞬,業(yè)務(wù)邏輯層,用來處理與業(yè)務(wù)相關(guān)的邏輯垫释。
-
完整項(xiàng)目結(jié)構(gòu)如下圖丝格。
- 配置文件及類文件如下,文件中注釋對(duì)配置進(jìn)行了說明棵譬。
- 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核心控制器,將所有的請(qǐng)求(除了剛剛Spring MVC中的靜態(tài)資源請(qǐng)求)都交給Spring MVC -->
<!-- DispatcherServlet上下文在初始化的時(shí)候會(huì)建立自己的IoC上下文,用以持有spring mvc相關(guān)的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>
<!--用來標(biāo)記是否在項(xiàng)目啟動(dòng)時(shí)就加在此Servlet,0或正數(shù)表示容器在應(yīng)用啟動(dòng)時(shí)就加載這個(gè)Servlet,
當(dāng)是一個(gè)負(fù)數(shù)時(shí)或者沒有指定時(shí)订咸,則指示容器在該servlet被選擇時(shí)才加載.正數(shù)值越小啟動(dòng)優(yōu)先值越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--為DispatcherServlet建立映射-->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!-- 攔截所有請(qǐng)求,千萬注意是(/)而不是(/*) -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 設(shè)置編碼過濾器 -->
<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">
<!--實(shí)體類匹配成XXXMapper.xml中可以直接使用的類型,相當(dāng)于一個(gè)別名酬诀,在XXXMapper.xml中就無需再寫完整的實(shí)體類全路徑脏嚷,直接用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"/>
<!--數(shù)據(jù)源-鏈接數(shù)據(jù)庫的基本信息-->
<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會(huì)自動(dòng)查找之中的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="site.wzhe.spring.demo.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!--事務(wù)管理-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource" />
</bean>
<!--開啟事務(wù)注解掃描-->
<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瞒御,
它會(huì)像一個(gè)檢查員父叙,對(duì)進(jìn)入DispatcherServlet的URL進(jìn)行篩查,如果發(fā)現(xiàn)是靜態(tài)資源的請(qǐng)求肴裙,
就將該請(qǐng)求轉(zhuǎn)由Web應(yīng)用服務(wù)器默認(rèn)的Servlet處理趾唱,如果不是靜態(tài)資源的請(qǐng)求,才由DispatcherServlet繼續(xù)處理蜻懦。 -->
<mvc:default-servlet-handler/>
<!-- 告知Spring甜癞,會(huì)自動(dòng)注冊(cè)DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個(gè)bean,是spring MVC為@Controllers分發(fā)請(qǐng)求所必須的。-->
<!--SpringMVC相關(guān)如下配置宛乃,經(jīng)過驗(yàn)證悠咱,這個(gè)是SpringMVC必須要配置的,因?yàn)樗暶髁薂RequestMapping征炼、@RequestBody析既、@ResponseBody等。并且谆奥,該配置默認(rèn)加載很多的參數(shù)綁定方法眼坏,比如json轉(zhuǎn)換解析器等。-->
<mvc:annotation-driven>
<!-- json請(qǐng)求無法通過@RequestBody轉(zhuǎn)為對(duì)象雄右,添加這個(gè)就可以解決-->
<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" />
<!-- 對(duì)靜態(tài)資源文件的訪問,因?yàn)镾pring MVC會(huì)攔截所有請(qǐng)求,導(dǎo)致jsp頁面中對(duì)js和CSS的引用也被攔截,配置后可以把對(duì)資源的請(qǐng)求交給項(xiàng)目的默認(rèn)servlet而不是Spring MVC-->
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
<!-- 為RequestMappingHandlerAdapter裝配可處理JSON格式的請(qǐng)求/響應(yīng)消息的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">
<!-- 有時(shí)我們需要訪問JSP頁面,可理解為在控制器controller的返回值加前綴和后綴,變成一個(gè)可用的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);
}
}
-
后面四個(gè)類文件對(duì)應(yīng)項(xiàng)目中類位置如下空骚。
3.5 通過游覽器輸入地址纺讲,測(cè)試項(xiàng)目是否運(yùn)行成功。
-
在游覽器地址欄輸入:localhost:8080/api/user/1
- 后端返回?cái)?shù)據(jù)囤屹。目前大多數(shù)項(xiàng)目都是前后端分離項(xiàng)目熬甚,后端返回?cái)?shù)據(jù),前端進(jìn)行渲染肋坚,展示給用戶乡括。所以,游覽器從后端返回Json格式的數(shù)據(jù)即可智厌。
如果對(duì)你有幫助诲泌,可以關(guān)注我,后續(xù)有更多詳細(xì)教程铣鹏。
原創(chuàng)文章,請(qǐng)勿用于商業(yè)用途,轉(zhuǎn)載請(qǐng)注明出處敷扫。
up