一、注解
1.@Controller定义控制器类,再使用注解@RequestMapping方法处理请求,完成映射关系。
2.@RestController等价于@Controller加上@ResponseBody
3.@PathVariable获取URI中的变量为参数。
@RequestMapping(value = "/product/{id}", method = RequestMethod.GET)
public String getProduct(@PathVariable("id") String id, Model model) throws Exception {
Product product = new Product();
product.setId(id);
product.setDescribe("this product is perfect and it id is " + id);
product.setName("product name");
product.setPrice(998.0f);
model.addAttribute("model", product);
return "product/show";
}
二、将URL映射到方法
1.假设接口请求所需要的参数id为123123这种情况下接口请求路径为127.0.0.1:8080/product/123123
这里需要使用 到@RequestMapping,SpringBoot中 提供了比较简洁的写法
@GetMapping:处理 get请求
@PostMapping:处理post请求
@DeleteMapping:处理删除请求
@PutMapping:处理修改请求
2.获取路径中的参数
@RequestMapping("/adduser")
public String adduser(String username){
}
这里的接口请求参数是靠=拼接的
如果请求参数usernameValue,那么完整的请求地址为
127.0.0.1:8080/adduser?username=usernameValue
3.接收路径中的json对象
public class addUser(UserModel user)
实际的实现
@RestController
public class className{
@RequestMapping("/")
public String addUser(@RequestBody Model model){
}
}
4.通过HttpServletRequest接收参数
@RequestMapping("/")
public String addUser(HttpServletRequest request){
request.GETParameter("username")
return "/index";
}
5.@RequestBody接收json数据
@RequestMapping(value = "adduser" , method = {RequestMethod.POST})
@ResponseBody
public void saveUser(@ResponseBody List<User> users){
}
6.上传文件,这里唯一的易忽略的点是上传文件的时候需要判断所在文件路径是否存在,判断文件是否存在,如果不存在就创建它们。
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public YZResult<String> uploadInfo(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
return YZResponse.makeErrRsp("请选择文件");
}
try {
System.out.println("-----------------------");
System.out.println("test file = ");
System.out.println(file);
byte[] bytes = file.getBytes();
String rootDir = getSavePath() + "\\";
Path path = Paths.get("/Users/macbookpro/Desktop/demo/src/main/resources/static/upload/fineagent.jar");
// File file1 = new File(String.valueOf(path));
// if (!file1.getParentFile().exists()) {
// System.out.println("i crate the file");
// file1.getParentFile().mkdirs();
// } else {
// System.out.println("file exists !");
// }
// System.out.println(path);
Files.write(path, bytes);
return YZResponse.makeOKRsp("you are successful upload file");
} catch (IOException e) {
System.out.println("-----------------------");
e.printStackTrace();
System.out.println("-----------------------");
}
return YZResponse.makeErrRsp("upload info fail");
}
public String getSavePath() {
// 这里需要注意的是ApplicationHome是属于SpringBoot的类
ApplicationHome applicationHome = new ApplicationHome(this.getClass());
// 保存目录位置根据项目需求可随意更改
return applicationHome.getDir().getParentFile()
.getParentFile().getAbsolutePath() + "/src/main/resources/static/upload";
}
long l = System.currentTimeMillis();
Date date = new Date(l);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String nyr = dateFormat.format(date);
@RequestMapping("/upimage")
public YZResult<String> upimage(@RequestParam("upimage") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.getOriginalFilename().endsWith(".jpg") || file.getOriginalFilename().endsWith(".png") || file.getOriginalFilename().endsWith(".gif")) {
try {
byte[] bytes = file.getBytes();
String basic = getSavePath() + "/";
String S = nyr + "Math.random() % 100" + "/" + file.getOriginalFilename();
String path = basic + S;
File file1 = new File(String.valueOf(path));
if (!file1.getParentFile().exists()) {
System.out.println("i crate the file");
file1.getParentFile().mkdirs();
} else {
System.out.println("file exists !");
}
Files.write(Paths.get(path), bytes);
return YZResponse.makeOKRsp("successful");
} catch (Exception e) {
e.printStackTrace();
}
return YZResponse.makeErrRsp("error");
} else {
return YZResponse.makeErrRsp("image type can only support png or jpg or gif,please check it in detail");
}
}
三、验证数据
验证器Hibernate-validator当前(2022.03.15)需要在pom.xml中添加一下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
一个神奇的功能,自定义注解类
接口文件MyCustomConstraint,注意这里如果是idea创建的Interface,前面会少个@符号,请对照自己添加
package com.example.demo;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyCustomConstraintValidator.class)
public @interface MyCustomConstraint {
String message() default "请输入中国政治经济中心城市名";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
还有验证的类MyCustomConstraintValidator
package com.example.demo;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class MyCustomConstraintValidator implements ConstraintValidator<MyCustomConstraint, String> {
@Override
public void initialize(MyCustomConstraint myCustomConstraint) {
//在启动时执行
}
@Override
public boolean isValid(String s, ConstraintValidatorContext validatorContext) {
if (!(s.equals("北京") || s.equals("上海"))) {
return false;
}
return true;
}
}
@MyCustomConstrain已经被定义,接下来看如何使用
1.创建实体Usr
package com.example.demo;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
import java.io.Serializable;
@Data
public class Usr implements Serializable {
private Long id;
@NotBlank(message = "用户名不能为空")
@Length(min = 5, max = 20, message = "用户名长度为5-20个字符")
private String name;
@NotNull(message = "年龄不能为空")
@Min(value = 18, message = "最小18岁")
@Max(value = 60, message = "最大60岁")
private Integer age;
@Email(message = "请输入邮箱")
@NotBlank(message = "邮箱不能为空")
private String email;
@MyCustomConstraint
private String answer;
}
2.验证控制器TestValidator的实现
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
@Controller
public class TestValidator {
@GetMapping("/test")
public String showFrom(Usr usr) {
return "form";
}
@GetMapping("/results")
public String results() {
return "results";
}
@PostMapping("/test")
public String checkUsr(@Valid Usr usr, BindingResult bindingResult, RedirectAttributes attr) {
if (bindingResult.hasErrors()) {
return "form";
}
attr.addFlashAttribute("usr", usr);
return "redirect:/results";
}
}
这里的addAttribute方法和addFlashAttribute的区别是前者将参数拼接到url后面,后者不会将参数拼接到url后面,而是将参数暂存在session中
3.视图form.html的实现,注意这里的"*{name}"可能会有底部红色波浪线提示报错,处理方法是将xmlne:th=""里面的www.去掉
<!DOCTYPE html>
<html lang="en" xmlns:th="http://thymeleaf.org">
<body>
<style type="text/css">
.warn {
color: red
}
</style>
<form th:action="@{/test}" th:object="${usr}" method="post">
<div>
<div>
<span>姓名:</span>
<span><input type="text" th:field="*{name}"/></span>
<span class="warn" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">名字错误</span>
</div>
<div>
<span>年龄:</span>
<span><input type="number" th:field="*{age}"/></span>
<span class="warn" th:if="${#fields.hasErrors('age')}" th:errors="*{age}">年龄错误</span>
</div>
<div>
<span>邮箱:</span>
<span><input TYPE="text" th:field="*{email}"/></span>
<span class="warn" th:if="${#fields.hasErrors('email')}" th:errors="*{email}">邮箱错误</span>
</div>
<div>
<span>验证答案:</span>
<span><input TYPE="text" th:field="*{answer}"/></span>
<span class="warn" th:if="${#fields.hasErrors('answer')}" th:errors="*{answer}">答案错误</span>
</div>
<div>
<span>
<button type="submit">提交</button>
</span>
</div>
</div>
</form>
</body>
</html>
视图结果results.html实现
<!DOCTYPE html>
<html lang="en" xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:each="usr:${usr}">
恭喜您,<span th:text="${usr.name}">名字</span>(先生/女士),数据提交成功!
<div>您的年龄是:
<span th:text="${usr.age}"></span>
</div>
</div>
<div>您的邮箱是:
<span th:text="${usr.email}"></span>
</div>
</body>
</html>
四、自定义返回YZResult类
1.错误码枚举YZCode enum
package com.example.demo;
public enum YZCode {
// 成功
SUCCESS(200),
// 失败
FAIL(400),
// 未认证(签名错误)
UNAUTHORIZED(401),
// 接口不存在
NOT_FOUND(404),
// 服务器内部错误
INTERNAL_SERVER_ERROR(500);
public int code;
YZCode(int code) {
this.code = code;
}
}
2.返回类YZResponse
package com.example.demo;
public class YZResponse {
private final static String SUCCESS = "success";
public static <T> YZResult<T> makeOKRsp() {
return new YZResult<T>().setCode(YZCode.SUCCESS).setMsg(SUCCESS);
}
public static <T> YZResult<T> makeOKRsp(T data) {
return new YZResult<T>().setCode(YZCode.SUCCESS).setMsg(SUCCESS).setData(data);
}
public static <T> YZResult<T> makeErrRsp(String message) {
return new YZResult<T>().setCode(YZCode.FAIL).setMsg(SUCCESS);
}
public static <T> YZResult<T> makeRsp(int code, String msg) {
return new YZResult<T>().setCode(code).setMsg(msg);
}
public static <T> YZResult<T> makeRsp(int code, String msg, T data) {
return new YZResult<T>().setCode(code).setMsg(msg).setData(data);
}
}
- YZResult
package com.example.demo;
public class YZResult<T> {
public int code;
private String msg;
private T data;
public YZResult<T> setCode(YZCode retCode) {
this.code = retCode.code;
return this;
}
public int getCode() {
return code;
}
public YZResult<T> setCode(int code) {
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public YZResult<T> setMsg(String msg) {
this.msg = msg;
return this;
}
public T getData() {
return data;
}
public YZResult<T> setData(T data) {
this.data = data;
return this;
}
}
使用:
@RequestMapping("/upimage")
public YZResult<String> upimage(@RequestParam("upimage") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.getOriginalFilename().endsWith(".jpg") || file.getOriginalFilename().endsWith(".png") || file.getOriginalFilename().endsWith(".gif")) {
try {
byte[] bytes = file.getBytes();
String basic = getSavePath() + "/";
String S = nyr + "Math.random() % 100" + "/" + file.getOriginalFilename();
String path = basic + S;
File file1 = new File(String.valueOf(path));
if (!file1.getParentFile().exists()) {
System.out.println("i crate the file");
file1.getParentFile().mkdirs();
} else {
System.out.println("file exists !");
}
Files.write(Paths.get(path), bytes);
return YZResponse.makeOKRsp("successful");
} catch (Exception e) {
e.printStackTrace();
}
return YZResponse.makeErrRsp("error");
} else {
return YZResponse.makeErrRsp("image type can only support png or jpg or gif,please check it in detail");
}
}
网友评论