SpringBoot開發後臺介面-1
前言:對於前端工程師在做應用時需要後臺提供資料庫中的資料到前臺顯示或是一些邏輯操作,此時自己不可能還專門找一個開發後臺的來給自己寫介面吧,這樣也會佔用人家的時間很麻煩,況且也是大材小用了,所以一些只涉及到只需要提供資料給前臺呼叫這樣的簡單操作就自己搞定吧,還好自己之前有些開發後臺的經驗,上手這樣的簡單操作應該問題不大哈,好了閒篇不扯了,這裡我們用到比較流行的Spring Boot框架來開發後臺介面,說實話我也是第一次用這個,有什麼不對的還請各位大神多指教哈!!! *執行環境:jdk 1.8 、mysql、maven專案構建 開發工具:IntelliJ IDEA 2017.3.5 x64、Navicat Premium、Tomcat 8.伺服器
<?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.spring.inter</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.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> <dependency> <groupId>org.springframework.restdocs</groupId> <artifactId>spring-restdocs-mockmvc</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
下面我們需要配置spring boot專案中使用到mysql資料庫和jpa方式處理資料
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
將以上的程式碼配置到pom.xml檔案dependencies標籤中
2.下面我們來配置application.properties檔案
server.port=8083
spring.jpa.show-sql = true
logging.level.org.springframework.data=DEBUG
spring.jpa.hibernate.ddl-auto=
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=jason
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.root是指定該專案執行的埠是8083,若是8083被其他程式佔用了你也可以使用其他的埠,自己定義
以上就表明配置了mysql資料庫是test資料庫使用者名稱和相對應的密碼(這些都是你安裝mysql後可以在doc命令中設定的哈)
3.下面就是將資料準備好,先配置mysql資料庫,這裡我有相應的sql檔案給到你們,本地已經配好了,開啟 Navicat Promium將本地的資料庫匯入連線起來 連線測試一下如果是成功的就進去了,失敗了你就要查查你的在配置mysql時的使用者名稱和密碼是否正確了!!! 我這裡使用user表中的資料來開發後臺介面返回其中的資料。 4.新建bean包下的User.class實體類(欄位和表中的欄位一樣) 類的名稱可以不一樣的,宣告@Table表明必須是user表
package com.spring.inter.demo.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
@Id
private long id;
@Column(name = "name")
private String name;
public User() {
}
public User(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5.新建repository包下JpaUserRepository介面繼承JpaRepository<T,ID> JpaRepository中包含對T型別的增刪改查操作
package com.spring.inter.demo.repository;
import com.spring.inter.demo.bean.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface JpaUserRepository extends JpaRepository<User,Long> {
}
6.新建service包下IUserService介面中定義對改User實體進行的操作方法
package com.spring.inter.demo.service;
import com.spring.inter.demo.bean.User;
import java.util.List;
public interface IUserService {
//獲取所有的使用者
List<User> getAllUser();
//增
int addUser(User user);
//刪
int deleteUser(long id);
//改
int updateUser(User User);
//查
User queryUser(long id);
}
7.在service中新建UserService實現IUserService 中定義的方法(定義返回的資料格式和程式中的錯誤碼代表的意思) 7.1錯誤碼:
package com.spring.comtroller.demo.result;
public interface ErrorCode {
/**
* 10000 網路繁忙
* 10001 無此使用者
* 10002 新增成功
* 10003 刪除成功
* 10004 更新成功
* 10005 此使用者已存在
* 10006 新增失敗
* 10007 刪除失敗
* 10008 更新失敗
* -1 請求失敗
* 0 請求成功
*/
int NETERROR = 10000;
int NOTEXISTUSER = 10001;
int ADDSUCCESS = 10002;
int DELETESUCCESS = 10003;
int UPDATESUCCESS = 10004;
int EXISTUSER = 10005;
int ADDFAIL = 10006;
int DELETEFAIL = 10007;
int UPDATEFAIL = 10008;
int REQUESTFAIL = -1;
int REQUESTSUCCESS = 0;
}
7.2返回的資料格式ResultModel
package com.spring.comtroller.demo.result;
import java.io.Serializable;
public class ResultModel implements Serializable{
private int code;
private String msg;
private Object data ;
public ResultModel() {
}
public ResultModel(int errorCode, String msg, Object data) {
this.code = errorCode;
this.msg = msg;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
7.3返回的資料處理工具類ResultModelTool.class
package com.spring.comtroller.demo.result;
import java.util.HashMap;
import java.util.Map;
public class ResultModelTool {
public static ResultModel handleResultModel(ResultModel resultModel) {
ResultModel handledModel = new ResultModel();
Map map = new HashMap();
if (resultModel != null) {
int error = resultModel.getCode();
handledModel.setCode(error);
switch (error) {
case 10000:
handledModel.setMsg("網路繁忙,請稍後重試");
handledModel.setData(map);
break;
case 10001:
handledModel.setMsg("無此使用者");
handledModel.setData(map);
break;
case 10002:
handledModel.setMsg("新增成功");
handledModel.setData(resultModel.getData());
break;
case 10003:
handledModel.setMsg("刪除成功");
handledModel.setData(resultModel.getData());
break;
case 10004:
handledModel.setMsg("更新成功");
handledModel.setData(resultModel.getData());
break;
case -1:
handledModel.setMsg("請求失敗");
handledModel.setData(map);
break;
case 10005:
handledModel.setMsg("此使用者已存在");
handledModel.setData(map);
break;
case 10006:
handledModel.setMsg("新增失敗");
handledModel.setData(map);
break;
case 10007:
handledModel.setMsg("刪除失敗");
handledModel.setData(map);
break;
case 10008:
handledModel.setMsg("更新失敗");
handledModel.setData(map);
break;
default:
handledModel.setMsg("請求成功");
handledModel.setData(resultModel.getData());
break;
}
}
return handledModel;
}
}
7.4實現User的增刪改查:
package com.spring.inter.demo.service;
import com.spring.inter.demo.bean.User;
import com.spring.inter.demo.repository.JpaUserRepository;
import com.spring.inter.demo.result.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService implements IUserService {
@Autowired
JpaUserRepository jpaUserRepository;
@Override
public List<User> getAllUser() {
List<User> users = jpaUserRepository.findAll();
System.out.println(users.toString());
return users;
}
@Override
public int addUser(User user) {
if (jpaUserRepository.existsById(user.getId())){
System.out.println("user is existed");
return ErrorCode.EXISTUSER;
}
User saveUser = jpaUserRepository.save(user);
if (saveUser != null && saveUser.getId() == user.getId()) {
System.out.println("save success");
return ErrorCode.ADDSUCCESS;
} else {
System.out.println("save failure");
return ErrorCode.ADDFAIL;
}
}
@Override
public int deleteUser(long id) {
if (jpaUserRepository.existsById(id)) {
jpaUserRepository.deleteById(id);
System.out.println("刪除成功");
return ErrorCode.DELETESUCCESS;
}
System.out.println("刪除失敗");
return ErrorCode.NOTEXISTUSER;
}
@Override
public int updateUser(User user) {
if (jpaUserRepository.existsById(user.getId())){
jpaUserRepository.save(user);
System.out.println("更新成功");
return ErrorCode.UPDATESUCCESS;
}
System.out.println("更新失敗");
return ErrorCode.UPDATEFAIL;
}
@Override
public User queryUser(long id) {
User user = null;
if (jpaUserRepository.existsById(id)){
user = jpaUserRepository.findById(id).get();
System.out.println(user.toString());
}
return user;
}
}
8.新建controller包下UserController類
package com.spring.inter.demo.controller;
import com.spring.inter.demo.bean.User;
import com.spring.inter.demo.result.ResultModel;
import com.spring.inter.demo.result.ResultModelTool;
import com.spring.inter.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/users")
public class UserController {
@Autowired
IUserService userService;
@RequestMapping(value = "/all",method = RequestMethod.GET)
public ResultModel getAllUser(){
List<User> userList = userService.getAllUser();
Map<String,List<User>> UserMap = new HashMap<>();
if (userList!=null){
UserMap.put("users",userList);
}
ResultModel resultModel = new ResultModel();
resultModel.setCode(0);
resultModel.setData(UserMap);
return ResultModelTool.handleResultModel(resultModel);
}
@PostMapping(value = "/addUser")
public ResultModel addUser(@RequestParam long id, @RequestParam String name){
User User = new User(id,name);
int errorCode = userService.addUser(User);
ResultModel resultModel = new ResultModel();
resultModel.setCode(errorCode);
resultModel.setData(User);
return ResultModelTool.handleResultModel(resultModel);
}
@PostMapping(value = "/updateUser")
public ResultModel updateUser(@RequestParam long id,@RequestParam String name){
User User = new User(id,name);
int errorCode = userService.updateUser(User);
ResultModel resultModel = new ResultModel();
resultModel.setCode(errorCode);
resultModel.setData(User);
return ResultModelTool.handleResultModel(resultModel);
}
@GetMapping(value = "/deleteUser/{id}")
public ResultModel deleteUser(@PathVariable long id){
int errorCode = userService.deleteUser(id);
ResultModel resultModel = new ResultModel();
resultModel.setCode(errorCode);
List<User> userList = userService.getAllUser();
Map<String,List<User>> UserMap = new HashMap<>();
if (userList!=null){
UserMap.put("users",userList);
}
resultModel.setData(UserMap);
return ResultModelTool.handleResultModel(resultModel);
}
}
執行該Spring boot專案就可以輸入地址進行訪問返回資料了 這樣就大功告成了哈!!!