首先创建项目就不细说了,先来配置pom文件:
<?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.tuc</groupId>
<artifactId>springdemo-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springdemo-1</name>
<description>spring</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 添加Tomcat部署依赖包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!--thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.2</version>
</dependency>
<!-- jdbc依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- pagehelper依赖 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
<!-- spring boot tomcat jsp 支持开启 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- devtools依赖 修改代码后即时重启启动 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
<build>
<finalName>springdemo-1</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
连接数据库配置application.properties文件中(test.sql数据库文件在底部下载文件中会有):
#mysql\u6570\u636E\u5E93\u914D\u7F6E
spring.datasource.url=jdbc:mysql://10.0.92.66:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=true
spring.datasource.username=test
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#\u5F00\u53D1\u65F6\u5173\u95ED\u7F13\u5B58,\u4E0D\u7136\u6CA1\u6CD5\u770B\u5230\u5B9E\u65F6\u9875\u9762
spring.thymeleaf.cache=false
#thymeleaf end
#uploadFileSize start
spring.http.multipart.maxFileSize=10Mb
spring.http.multipart.maxRequestSize=100Mb
#uploadFileSize end
创建model UserInfo.java:
package com.tuc.model;
public class UserInfo {
private Integer id;
private String name;
private Integer age;
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
创建返回前端数据的model ResultModel.java:
package com.tuc.model;
import java.util.Map;
public class ResultModel {
private int errcode;// 返回码
private String errmsg;// 返回消息
private Map<String, Object> data;// 数据源
public int getErrcode() {
return errcode;
}
public void setErrcode(int errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
}
创建请求结果处理类ResultTools.java:
package com.tuc.util;
import java.util.Map;
import com.tuc.model.ResultModel;
/**
* 请求结果处理类
*/
public class ResultTools {
/****
* 错误码记录:
* 0--------成功
* 1001-----请求传参错误
* 1002-----没有对应内容
* 1003-----此用户已存在
* 1004-----上传文件为空
* 404------异常抛出错误
*
*/
/**
* @param Errcode--返回码
* @param Errmsg---404服务器内部异常时提示消息(返回码不是404时传空即可)
* @param map------数据源
* @return
*/
public static ResultModel result(int Errcode, String Errmsg, Map<String, Object> map) {
ResultModel model = new ResultModel();
model.setErrcode(Errcode);
switch (Errcode) {
case 0:
model.setErrmsg("成功");
if (map != null) {
model.setData(map);
}
break;
case 1001:
model.setErrmsg("请求传参错误 ");
break;
case 1002:
model.setErrmsg("没有对应内容 ");
break;
case 1003:
model.setErrmsg("此用户已存在");
break;
case 1004:
model.setErrmsg("上传文件为空");
break;
case 404:
model.setErrmsg(Errmsg);
break;
default:
model.setErrmsg("未知错误");
break;
}
return model;
}
}
接下来写数据库操作类UserMapper.java:
package com.tuc.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.tuc.model.UserInfo;
public interface UserMapper {
/*******查询所有用户数据********/
@Select("select * from user")
public List<UserInfo> selectUserByAll();
/*******根据id查询符合用户********/
@Select("select * from user where id = #{id}")
public UserInfo selectUserById(int id);
/*******根据name查询符合用户********/
@Select("select * from user where name=#{name}")
public List<UserInfo> selectUserByName(String name);
/*******添加新用户********/
@Insert("insert into user(name,age,phone) values (#{name},#{age},#{phone})")
public int addUser(UserInfo user);
/*******修改已有用户信息********/
@Update("update user set name=#{name},age=#{age},phone=#{phone} where id=#{id}")
public int updateUser(UserInfo user);
/*******根据id删除用户********/
@Delete("delete from user where id=#{id}")
public int deleteUser(int id);
}
在程序入口类中进行配置:
package com.tuc;
import java.util.Properties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.context.annotation.Bean;
import com.github.pagehelper.PageHelper;
@SpringBootApplication
@MapperScan("com.tuc.mapper") // 告诉Mapper所在的包名
public class Springdemo1Application implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
configurableEmbeddedServletContainer.setPort(8080);// 修改端口号
}
public static void main(String[] args) {
SpringApplication.run(Springdemo1Application.class, args);
}
@Bean
public PageHelper pageHelper() {// 配置myBatis的分页插件pageHelper
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
然后写逻辑处理类 UserController.java:
package com.tuc.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageHelper;
import com.tuc.mapper.UserMapper;
import com.tuc.model.ResultModel;
import com.tuc.model.UserInfo;
import com.tuc.util.ResultTools;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping(value = { "/selectUserByAll" }, method = RequestMethod.GET)
public ResultModel selectUserByAll() {
try {
List<UserInfo> userLs = userMapper.selectUserByAll();
Map<String, Object> map = new HashMap<String, Object>();
map.put("content", userLs);
return ResultTools.result(0, "", map);
} catch (Exception e) {
return ResultTools.result(404, e.getMessage(), null);
}
}
@RequestMapping(value = { "/selectUserById" }, method = RequestMethod.GET)
public ResultModel selectUserById(Integer id) {
try {
if (null == id) {
return ResultTools.result(1001, "", null);
}
UserInfo user = userMapper.selectUserById(id);
if (null == user) {
return ResultTools.result(1002, "", null);
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("content", user);
return ResultTools.result(0, "", map);
} catch (Exception e) {
return ResultTools.result(404, e.getMessage(), null);
}
}
@RequestMapping(value = { "/selectUserByName" }, method = RequestMethod.GET)
public ResultModel selectUserByName(String name, Integer page, Integer pageSize) {
try {
if (null == name) {
return ResultTools.result(1001, "", null);
}
PageHelper.startPage(page, pageSize);// 分页配置
List<UserInfo> userLs = userMapper.selectUserByName(name);
Map<String, Object> map = new HashMap<String, Object>();
map.put("content", userLs);
return ResultTools.result(0, "", map);
} catch (Exception e) {
return ResultTools.result(404, e.getMessage(), null);
}
}
@RequestMapping(value = { "/addUser" }, method = RequestMethod.POST)
public ResultModel addUser(UserInfo user) {
try {
int code = userMapper.addUser(user);
if (1 == code) {
return ResultTools.result(0, "", null);
}
return ResultTools.result(404, "失败", null);
} catch (Exception e) {
return ResultTools.result(404, e.getMessage(), null);
}
}
@RequestMapping(value = { "/updateUser" }, method = RequestMethod.POST)
public ResultModel updateUser(UserInfo user) {
try {
int code = userMapper.updateUser(user);
if (1 == code) {
return ResultTools.result(0, "", null);
}
return ResultTools.result(404, "失败", null);
} catch (Exception e) {
return ResultTools.result(404, e.getMessage(), null);
}
}
@RequestMapping(value = { "/deleteUser" }, method = RequestMethod.POST)
public ResultModel deleteUser(String id) {
try {
int code = userMapper.deleteUser(Integer.parseInt(id));
if (1 == code) {
return ResultTools.result(0, "", null);
}
return ResultTools.result(404, "失败", null);
} catch (Exception e) {
return ResultTools.result(404, e.getMessage(), null);
}
}
}
以上就可以实现简单的后台接口功能,将程序跑起来,测试下:
调用接口http://localhost:8080/selectUserByAll
最后附上完整Demo下载链接:http://download.csdn.net/download/qq_29370483/10202696
Demo中还实现了文件上传,有兴趣的可以下载看看。