Spring Boot寫後臺介面
阿新 • • 發佈:2019-02-01
首先建立專案就不細說了,先來配置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資料庫檔案在底部下載檔案中會有):
建立model UserInfo.java:#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 ResultModel.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; } }
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中還實現了檔案上傳,有興趣的可以下載看看。