轻松入门springboot之web
springmvc
在springboot中使⽤springmvc⾮常简单,只需要引⼊⼀个starter即可:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
对于前后端分离的项⽬,前后端之间的交互⼤多数是采⽤json的形式来传递数据,在这种情况下,数据的展现完全由前端负责,后端只需要把数据相关的接⼝暴露出来让前端去进⾏请求调⽤即可。
在不考虑视图层的数据展现问题的情况下,后端可以创建出RSETFul⻛格的接⼝,供前端进⾏调⽤访问。
REST(Representational State Transfer),是2000年Roy Fielding博⼠在他的博⼠论⽂中所提出的⼀种软件架构模式。
REST就是⼀种设计API的模式。最常⽤的数据格式是JSON。由于JSON能直接被JavaScript读取,所以,以JSON格式编写的REST⻛格的API具有简单、易读、易⽤的特点。
RESTful的web服务是⼀种⾯向资源的架构设计,ROA(The Resource-Oriented Architecture)。
传统风格接口:
RESTFul风格接口
创建项目springboot-web-restful :
pom.xml⽂件: 只需引⼊web相应的starter即可
<?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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.briup</groupId>
<artifactId>springboot-web-restful</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-web-restful</name>
<description>Demo project for Spring Boot</description>
<properties>
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
User 类:
package com.briup.bean;
public class User {
private long id;
private String name;
private int age;
public User() {}
public User(long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
ResultCode 类:
package com.briup.util;
/**
* 统⼀并⾃定义返回状态码,如有需求可以另外增加
*/
public enum ResultCode {
/* 成功状态码 */
SUCCESS(1, "操作成功"),
/* 参数错误:10001-19999 */
PARAM_IS_INVALID(10001, "参数⽆效"),
PARAM_IS_BLANK(10002, "参数为空"),
PARAM_TYPE_BIND_ERROR(10003, "参数类型错误"),
PARAM_NOT_COMPLETE(10004, "参数缺失"),
/* ⽤户错误:20001-29999*/
USER_NOT_LOGIN(20001, "⽤户未登录"),
USER_LOGIN_ERROR(20002, "账号不存在或密码错误"),
USER_ACCOUNT_FORBIDDEN(20003, "账号已被禁⽤"),
USER_NOT_EXIST(20004, "⽤户不存在"),
USER_HAS_EXISTED(20005, "⽤户已存在"),
/* 业务错误:30001-39999 */
SPECIFIED_QUESTIONED_USER_NOT_EXIST(30001, "业务逻辑出现问题"),
/* 系统错误:40001-49999 */
SYSTEM_INNER_ERROR(40001, "系统内部错误,请稍后重试"),
/* 数据错误:50001-599999 */
DATA_NONE(50001, "数据未找到"),
DATA_WRONG(50002, "数据错误"),
DATA_EXISTED(50003, "数据已存在"),
/* 接⼝错误:60001-69999 */
INTERFACE_INNER_INVOKE_ERROR(60001, "内部系统接⼝调⽤异常"),
INTERFACE_OUTTER_INVOKE_ERROR(60002, "外部系统接⼝调⽤异常"),
INTERFACE_FORBID_VISIT(60003, "该接⼝禁⽌访问"),
INTERFACE_ADDRESS_INVALID(60004, "接⼝地址⽆效"),
INTERFACE_REQUEST_TIMEOUT(60005, "接⼝请求超时"),
/* 权限错误:70001-79999 */
PERMISSION_NO_ACCESS(70001, "⽆访问权限");
private Integer code;
private String message;
ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer code() {
return this.code;
}
public String message() {
return this.message;
}
}
Result 类:
package com.briup.util;
import java.io.Serializable;
/**
* 统⼀Controller中RESTFul⻛格接⼝返回的结果
*/
public class Result implements Serializable {
private static final long serialVersionUID = 1L;
private Integer code;
private String msg;
private Object data;
public Result() {}
public Result(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
private void setResultCode(ResultCode code) {
this.code = code.code();
this.msg = code.message();
}
/**
* 操作成功,没有返回的数据
*/
public static Result success() {
Result result = new Result();
result.setResultCode(ResultCode.SUCCESS);
return result;
}
/**
* 操作成功,有返回的数据
*/
public static Result success(Object data) {
Result result = new Result();
result.setResultCode(ResultCode.SUCCESS);
result.setData(data);
return result;
}
/**
* 操作失败,没有返回的数据
*/
public static Result failure(ResultCode resultCode) {
Result result = new Result();
result.setResultCode(resultCode);
return result;
}
/**
* 操作失败,有返回的数据
*/
public static Result failure(ResultCode resultCode, Object data) {
Result result = new Result();
result.setResultCode(resultCode);
result.setData(data);
return result;
}
public Integer getCode() {
return code;
}
public void setCode(Integer 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;
}
}
UserController 类:
package com.briup.controller;
import java.util.Random;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.briup.bean.User;
import com.briup.util.Result;
import com.briup.util.ResultCode;
@RestController
public class UserController {
@GetMapping("/user/{userId}")
public Result query(@PathVariable("userId") long userId) {
//随机成功或者失败
int random = new Random().nextInt(10);
if(random%2==0) {
User user = new User(userId,"tom",20);
return Result.success(user);
}
else {
return Result.failure(ResultCode.USER_NOT_EXIST);
}
}
@PostMapping("/user")
public Result create(@RequestBody User user) {
//随机成功或者失败
int random = new Random().nextInt(10);
if(random%2==0) {
user.setId(1L);
return Result.success(user);
}
else {
return Result.failure(ResultCode.PERMISSION_NO_ACCESS);
}
}
@PutMapping("/user")
public Result update(@RequestBody User user) {
//随机成功或者失败
int random = new Random().nextInt(10);
if(random%2==0) {
return Result.success(user);
}
else {
return Result.failure(ResultCode.USER_ACCOUNT_FORBIDDEN);
}
}
@DeleteMapping("/user/{id}")
public Result delete(@PathVariable("id") long id) {
//随机成功或者失败
int random = new Random().nextInt(10);
if(random%2==0) {
return Result.success();
}
else {
return Result.failure(ResultCode.USER_NOT_EXIST);
}
}
}
注意,当前application.properties配置⽂件中的内容为空,全是采⽤的默认配置。
启动这个基于springboot框架构建的web项⽬,默认采⽤项⽬中内嵌的tomcat,端⼝号8080,其他所有配置全是采⽤springboot框架的默认配置。
在STS中常⽤的三中启动方式:
- 直接以java程序的⽅式运⾏程序⼊⼝类:Application.java
- 使⽤mvn的⽅式运⾏springboot插件的指定goal
- 使⽤STS中提供好的⽅式
以上三种⽅式,都可以正常启动该web项⽬,看到如下结果
注意,如果遇到端⼝被占⽤了,可以使⽤如下命令解决
windows中:
netstat -aon|findstr 8080
显示结果: TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 2696
taskkill /F /pid 2696
显示结果: 成功: 已终⽌ PID 为 2696 的进程。
在Ubuntu中:
netstat -anp | grep :8080
kill -9 2696
项目启动完成后需要进行测试,详情之后讲解
- 点赞
- 收藏
- 关注作者
评论(0)