【JavaEE】SpringMVC简单练习_javaee9之后如何测试springmvc
目录
- 一、计算器
- 二、⽤⼾登录
-
- 2.1 需求
- 2.2 接口定义
- 2.3 前端页面
- 2.4 后端代码
- 2.5 结果
- 三、留⾔板
-
- 3.1 需求:
- 3.2 接口
- 3.3 前端代码
- 3.4 后端代码
- 3.5 运行结果
- 四、图书管理系统
-
- 4.1 需求
- 4.2 接口定义
- 4.3 后端代码
一、计算器
1.1 接口定义
请求路径:calc/sum
请求⽅式:GET/POST
接⼝描述:计算两个整数相加
请求路径:calc/sub
请求⽅式:GET/POST
接⼝描述:计算两个整数相减
请求路径:calc/mul
请求⽅式:GET/POST
接⼝描述:计算两个整数相乘
请求路径:calc/div
请求⽅式:GET/POST
接⼝描述:计算两个整数相除
请求参数:
响应数据:
Content-Type: text/html
示例:num1=5&num2=3
响应内容: 计算机计算结果: 8
1.2 前端代码
前端代码如下:
<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> <form action=\"/calc/sum\" method=\"post\"> <h1>计算器</h1> 数字1:<input name=\"num1\" type=\"text\"><br> 数字2:<input name=\"num2\" type=\"text\"><br> <input type=\"submit\" value=\" 点击相加 \"> </form> <form action=\"/calc/sub\" method=\"post\"> 数字1:<input name=\"num1\" type=\"text\"><br> 数字2:<input name=\"num2\" type=\"text\"><br> <input type=\"submit\" value=\" 点击相减 \"> </form> <form action=\"/calc/mul\" method=\"post\"> 数字1:<input name=\"num1\" type=\"text\"><br> 数字2:<input name=\"num2\" type=\"text\"><br> <input type=\"submit\" value=\" 点击相乘 \"> </form> <form action=\"/calc/div\" method=\"post\"> 数字1:<input name=\"num1\" type=\"text\"><br> 数字2:<input name=\"num2\" type=\"text\"><br> <input type=\"submit\" value=\" 点击相除 \"> </form></body></html>
1.3 后端代码
后端代码如下:
只需要处理一下非法输入即可。
package com.example.project;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RequestMapping(\"/calc\")@RestControllerpublic class CalcController { @RequestMapping(\"/sum\") //加 public String sum(Integer num1, Integer num2) { Integer ret = null; if(null == num1 || null == num2) { return \"错误输入\"; } ret = num1 + num2; return \"计算机计算结果: \"
+ ret+\"\"; } @RequestMapping(\"/sub\") //减 public String sub(Integer num1, Integer num2) { Integer ret = null; if(null == num1 || null == num2) { return \"错误输入\"; } ret = num1 - num2; return \"计算机计算结果: \"
+ ret +\"\"; } @RequestMapping(\"/mul\") //乘 public String mul(Integer num1, Integer num2) { Integer ret = null; if(null == num1 || null == num2) { return \"错误输入\"; } ret = num1 * num2; return \"计算机计算结果: \"
+ ret+\"\"; } @RequestMapping(\"/div\") //除 public String div(Integer num1, Integer num2) { Float ret = null; if(null == num1 || null == num2 || 0 == num2) { return \"错误输入\"; } ret = num1 / (float) num2; return \"计算机计算结果: \"
+ ret+\"\"; }}
1.4 运行结果
结果如下:
二、⽤⼾登录
2.1 需求
⽤⼾输⼊账号和密码, 后端进⾏校验密码是否正确
- 如果不正确, 前端进⾏⽤⼾告知
- 如果正确, 跳转到⾸⻚. ⾸⻚显⽰当前登录⽤⼾
- 后续再访问⾸⻚, 可以获取到登录⽤⼾信息
2.2 接口定义
校验接⼝
请求路径:/user/login
请求⽅式:POST
接⼝描述:校验账号密码是否正确
请求参数:
响应:
Content-Type: text/html
响应内容:
true //账号密码验证成功
false//账号密码验证失败
查询登录⽤⼾接⼝
请求路径:/user/getLoginUser
请求⽅式:GET
接⼝描述:查询当前登录的⽤⼾
响应:
Content-Type: text/html
响应内容:
zhangsan
2.3 前端页面
登录⻚⾯login.html
<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>登录页面</title></head><body> <h1>用户登录</h1> 用户名:<input name=\"userName\" type=\"text\" id=\"userName\"><br> 密码:<input name=\"password\" type=\"password\" id=\"password\"><br> <input type=\"button\" value=\"登录\" onclick=\"login()\"> <script src=\"https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js\"></script> <script> function login() { $.ajax({ type: \"post\", url: \"/user/login\", data: { \"userName\": $(\"#userName\").val(), \"password\": $(\"#password\").val() }, success: function (result) { if (result) { location.href = \"/index.html\" } else { alert(\"账号或密码有误.\"); } } }); } </script></body></html>
⾸⻚代码index.html
<!doctype html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>用户登录首页</title></head><body> 登录人: <span id=\"loginUser\"></span> <script src=\"https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js\"></script> <script> $.ajax({ type: \"get\", url: \"/user/getLoginUser\", success: function (result) { $(\"#loginUser\").text(result); } }); </script></body></html>
2.4 后端代码
StringUtils.hasLength方法是说如果字符串为空或者没长度,返回false。
由于没有数据库,直接写死。
package com.example.project;import ch.qos.logback.core.util.StringUtil;import jakarta.servlet.http.HttpSession;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RequestMapping(\"/user\")@RestControllerpublic class LoginController { @RequestMapping(\"/login\") public Boolean login(String userName, String password, HttpSession session) { if(StringUtils.hasLength(userName) && StringUtils.hasLength(password) && \"1234\".equals(password)) ) { session.setAttribute(\"userName\",userName); return true; } else return false; } @RequestMapping(\"/getLoginUser\") public String getLoginUser(HttpSession session) { String userName = (String)session.getAttribute(\"userName\"); if(StringUtils.hasLength(userName)) { return userName; } else { return \"\"; } }}
2.5 结果
运行结果如下:
三、留⾔板
3.1 需求:
界⾯如下
- 输⼊留⾔信息,点击提交 后端把数据存储起来.
- ⻚⾯展⽰输⼊的表⽩墙的信息
3.2 接口
获取全部留⾔:
请求:
GET /message/getList
响应:JSON 格式
[ { \"from\": \"⿊猫\", \"to\": \"⽩猫\", \"message\": \"喵\" },{ \"from\": \"⿊狗\", \"to\": \"⽩狗\", \"message\": \"汪\" }, //...]
发表新留⾔:
请求: body 也为 JSON格式.
POST /message/publish
{ \"from\": \"⿊猫\", \"to\": \"⽩猫\", \"message\": \"喵\"}
响应: JSON格式.
{ ok: 1}
3.3 前端代码
前端代码如下:
<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>留言板</title> <style> .container { width: 350px; height: 300px; margin: 0 auto; /* border: 1px black solid; */ text-align: center; } .grey { color: grey; } .container .row { width: 350px; height: 40px; display: flex; justify-content: space-between; align-items: center; } .container .row input { width: 260px; height: 30px; } #submit { width: 350px; height: 40px; background-color: orange; color: white; border: none; margin: 10px; border-radius: 5px; font-size: 20px; } </style></head><body> <div class=\"container\"> <h1>留言板</h1> <p class=\"grey\">输入后点击提交, 会将信息显示下方空白处</p> <div class=\"row\"> <span>谁:</span> <input type=\"text\" name=\"\" id=\"from\"> </div> <div class=\"row\"> <span>对谁:</span> <input type=\"text\" name=\"\" id=\"to\"> </div> <div class=\"row\"> <span>说什么:</span> <input type=\"text\" name=\"\" id=\"say\"> </div> <input type=\"button\" value=\"提交\" id=\"submit\" onclick=\"submit()\"> <!-- A 对 B 说: hello --> </div> <script src=\"https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js\"></script> <script> function submit(){ //1. 获取留言的内容 var from = $(\'#from\').val(); var to = $(\'#to\').val(); var say = $(\'#say\').val(); if (from== \'\' || to == \'\' || say == \'\') { return; } //2. 构造节点 var divE = \"\"+from +\"对\" + to + \"说:\" + say+\"\"; //3. 把节点添加到页面上 $(\".container\").append(divE); //4. 清空输入框的值 $(\'#from\').val(\"\"); $(\'#to\').val(\"\"); $(\'#say\').val(\"\"); } </script></body></html>
3.4 后端代码
为储存输入的信息,我们要使用一个对象:
lombok依赖,在这个包下有很多注解来表示类的get和set和hashcode等等方法。
@Data=@Getter+@Setter+@ToString+@EqualsAndHashCode+@RequiredArgsConstructor
+@NoArgsConstructor
package com.example.project;import lombok.Data;@Datapublic class MessageInfo { private String from; private String to; private String message;}
还是由于没连接数据库,存在一个顺序表中
package com.example.project;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;import java.util.List;@RestController@RequestMapping(\"/message\")public class MessageController { List<MessageInfo> messageInfos = new ArrayList<>(); @RequestMapping(\"/getList\") public List<MessageInfo> getList() { return messageInfos; } @RequestMapping(value = \"/publish\", produces = \"application/json\") public boolean publish(MessageInfo messageInfo) { if (StringUtils.hasLength(messageInfo.getFrom()) && StringUtils.hasLength(messageInfo.getTo()) && StringUtils.hasLength(messageInfo.getMessage())) { messageInfos.add(messageInfo); return true; } else { return false; } }}
3.5 运行结果
运行结果如下:
四、图书管理系统
4.1 需求
后端需要提供两个接⼝
- 账号密码校验接 : 根据输⼊⽤⼾名和密码校验登录是否通过
- 图书列表: 提供图书列表信息
4.2 接口定义
- 登录接口:
[URL]
POST /user/login
[请求参数]
name=admin&password=admin
[响应]
true //账号密码验证成功
false//账号密码验证失败
- 图书列表展⽰
[URL]
POST /book/getList
[请求参数]
⽆
[响应]
返回图书列表[ { \"id\": 1, \"bookName\": \"活着\", \"author\": \"余华\", \"count\": 270, \"price\": 20, \"publish\": \"北京⽂艺出版社\", \"status\": 1, \"statusCN\": \"可借阅\" },...
4.3 后端代码
前端代码太多,不展示了,在bookstrap上找模板。
图书信息:
package com.example.project;import lombok.Data;import java.math.BigDecimal;import java.util.Date;@Datapublic class BookInfo { //图书ID private Integer id; //书名 private String bookName; //作者 private String author; //数量 private Integer count; //定价 private BigDecimal price; //出版社 private String publish; //状态 0-⽆效 1-允许借阅 2-不允许借阅 private Integer status; private String statusCN; //创建时间 private Date createTime; //更新时间 private Date updateTime;}
图书接口:
package com.example.project;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import java.util.Random;@RequestMapping(\"/book\")@RestControllerpublic class BookController { public List<BookInfo> mockData() { List<BookInfo> books = new ArrayList<>(); for (int i = 0; i < 5; i++) { BookInfo book = new BookInfo(); book.setId(i); book.setBookName(\"书籍\" + i); book.setAuthor(\"作者\" + i); book.setCount(i * 5 + 3); book.setPrice(new BigDecimal(new Random().nextInt(100))); book.setPublish(\"出版社\" + i); book.setStatus(1); books.add(book); } return books; } @RequestMapping(\"/getList\") public List<BookInfo> getList() { List<BookInfo> books = new ArrayList<>(); books = mockData(); for (BookInfo book: books) { if(book.getStatus() == 1) { book.setStatusCN(\"可借阅\"); } else { book.setStatusCN(\"不可借阅\"); } } return books; }}
登录接口:
package com.example.project;import ch.qos.logback.core.util.StringUtil;import jakarta.servlet.http.HttpSession;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RequestMapping(\"/user\")@RestControllerpublic class LoginController { @RequestMapping(\"/login\") public Boolean login(String userName, String password, HttpSession session) { if(StringUtils.hasLength(userName) && StringUtils.hasLength(password) && \"admin\".equals(password) && \"admin\".equals(userName)) { session.setAttribute(\"userName\",userName); return true; } else return false; } @RequestMapping(\"/getLoginUser\") public String getLoginUser(HttpSession session) { String userName = (String)session.getAttribute(\"userName\"); if(StringUtils.hasLength(userName)) { return userName; } else { return \"\"; } }}