javaEE-14.spring MVC练习

devtools/2025/2/24 3:35:31/

目录

1.加法计算器

需求分析:

前端页面代码:

后端代码实现功能:

调整前端页面代码:

进行测试:

2.用户登录

需求分析:

定义接口:

1.登录数据校验接口:

2.查询登录用户接口:

前端代码:

后端代码:

调整前端代码:

测试/查错因

后端:

前端:

lombok工具

1.引入依赖:

2.使用

3.原理

3.留言板

需求分析:

接口定义:

前端代码:

后端代码:

前端代码完善功能:


1.加法计算器

需求: 输⼊两个整数, 点击"点击相加"按钮, 显⽰计算结果

在项⽬开发前,根据需求先约定好前后端交互接⼝,双⽅按照接 ⽂档进⾏开发.

接⼝⽂档通常由服务提供⽅来写,交由服务使⽤⽅确认,也就是客⼾端.

 接⼝⽂档⼀旦写好,尽量不要轻易改变. 如若需要改变,必须要通知另⼀⽅知晓

需求分析:

 加法计算器功能,对两个整数进⾏相加, 需要客⼾端提供参与计算的两个数,服务端返回这两个整数计算 的结果.

基于上述分析,定义接口(这里的接口不是java初阶的interface接口,而是前后端交互的路径接口):

1.请求路径:calc/sum

2.请求方法:get/post

3.接口描述:计算两个整数相加

请求参数:

参数名类型描述
num1Integer参与计算的第一个参数
num2Integer参与计算的第二个参数

响应数据:

Content-Type:  text/html

响应内容:  计算机计算结果: 8

前端页面代码:

<!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>
</body></html>

浏览器测试页面是否正常:路径以static为根目录进行遍历

前端代码正常.

后端代码实现功能:

package com.springmvc.test;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RequestMapping("/calc")
@RestController
public class calcController {@RequestMapping("/sum")public String getSum(Integer num1,Integer num2){Integer sum=num1+num2;return "计算器计算结果为:"+sum;}
}

通过Postman对后端代码进行测试:

通过响应结果可以看到 后端代码正常.

调整前端页面代码:

添加访问url和请求⽅式

进行测试:

点击相加:

2.用户登录

需求:⽤⼾输⼊账号和密码,后端进⾏校验密码是否正确

 1. 如果不正确,前端进⾏⽤⼾告知

 2. 如果正确,跳转到⾸⻚.⾸⻚显⽰当前登录⽤⼾

 3. 后续再访问⾸⻚,可以获取到登录⽤⼾信息

需求分析:

1.登录界面:通过账号和密码,校验输入的账号和密码是否正确,并告诉前端.

2.首页:告知前端当前登录⽤⼾. 如果当前已有⽤⼾登录, 返回登录的账号,如果没有,返回空

定义接口:

1.登录数据校验接口:

请求路径:/user/login

请求⽅式:POST

接⼝描述:校验账号密码是否正确

请求参数:

参数名类型
userNameString
passwordString

响应数据:

Content-type: text/html

响应内容 : true //账号密码验证成功

                 false//账号密码验证失败

2.查询登录用户接口:

请求路径:/use/index

请求⽅式:get

接⼝描述:查询当前登录的用户

请求参数:无

响应数据:

Content-type: text/html

响应内容 :zhangsan

前端代码:

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() {}</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></script>
</body></html>

后端代码:

由于要在首页中获取登录人的用户名,因此,在登录方法中,要设置SessionId,将登录信息保存下来,在获取登录人信息时,进行返回.

注意:

 1.对数据的校验可以通过:StringUtils.hasLength()方法来进行校验.

StringUtils.hasLength()是Spring提供的⼀个⼯具⽅法,判断字符串是否有值,字符串为null或者""时,返回false,其他返回true.

 2. 使用equals方法的时候,建议将常量放在前面,变量放在后面.(防止出现空指针异常)

package com.springmvc.test;import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;@RestController
@RequestMapping("/user")
public class loginController {@RequestMapping("/login")public Boolean login(String userName, String password, HttpSession session){
//        1.数据校验//法一:
//        if(userName==null || userName.length()==0 || password==null || password.length()==0){
//               return false;
//        }//法二if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){return false;}//判断:
//       使用equals方法时,通常将常量写在前面,目的:防 useraName为null,报空指针异常if("zhangsan".equals(userName) && "123456".equals(password)){session.setAttribute("userName",userName);return true;}return false;}@RequestMapping("/index")public String getUserName(@SessionAttribute("userName")String userName){return userName;}
}

调整前端代码:

对于前端⽽⾔, 当点击登录按钮时, 需要把⽤⼾输⼊的信息传递到后端进⾏校验, 后端校验成功,则跳转 到⾸⻚:index.html, 后端校验失败,则直接弹窗

login.html:


<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>function login() {$.ajax({// URL:url:"user/login",// 请求方法:type:"post",// 参数data:{userName:$("#userName").val(),password:$("#password").val()},// http响应成功:success:function(result){if(result==true){location.href="index.html";}else{alert("密码错误!");}}});}</script>

页面跳转3种方法:

window.location.href="index.html";

window.loction.assign( "index.html");

window.location.replace( "index.html");

通常把window. 省略,常用前两种方法.

index.html:


<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>$.ajax({url:"user/index",type:"get",success:function(name){$("#loginUser").text(name);}});
</script>

测试/查错因

后端:

代码功能完成后,

        1>.可通过Postman进行测试,

        2>.若测试能通过,后续再出现问题几乎就不是后端问题了.

        3>.若没有通过,可能是后端有缓存,刷新Maven:clean,然后重启spring,再次测试.

        4>.若还是出错,可以通过看日志的方法,(看不懂,可以上网查)

        5>.通过debug,打断点的方法,进行调试

前端:

        1>.通过打日志的方法  : console.log() / alert()方法

        2>.前端打断点:

lombok工具

lombok是一个java工具库,通过添加注解,简化java代码的开发.

1.引入依赖:

通过在pom.xml文件中导入依赖:

 <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>annotationProcessor</scope></dependency>

快捷引入方式:要先下载一个插件:EditStarter

然后选择pom文件,右键:选择生成->EditStarter

->选择lombok进行添加就行:

注意: 不是所有的依赖都能从EditStarter添加,依赖不在的时候,还有从Maven仓库去找,再粘贴依赖代码.

还可以在创建项目的时候,勾选lombok工具包:

若创建的时候,没有勾选,在开发的时候也可以再添加:选中pom文件,点击编辑启动器,进行添加.(这个和上面的通过EditStarter方法相同)

2.使用

在写一些对象类的时候,通过⼀些注解的⽅式,可以帮助我们消除⼀些冗⻓代码,使代码看起来简洁⼀些

比如user类:

@Data注解,可以帮助我们自动完成一些方法:getter(),setter(),toString(),equals()等.

@Data这个注解的功能比较强大,lombok还有一些更细粒度的注解:

@Data  = @Getter+@Setter+@ToString+@EqualsAndHashCode +@RequiredArgsConstructor + @NoArgsConstructor

3.原理

添加@Data注解后,可以看idea运行后反编译的class文件:

class文件中就能看到 lombok实现的代码了

java程序的运行原理:

加上lombok后:

3.留言板

需求: 界⾯如下图所⽰

         1. 输⼊留⾔信息,点击提交.后端把数据存储起来.

          2. ⻚⾯展⽰输⼊的表⽩墙的信息

需求分析:

后端需要提供两个服务

1. 提交留⾔:⽤⼾输⼊留⾔信息之后,后端需要把留⾔信息保存起来

2. 展⽰留⾔:⻚⾯展⽰时,需要从后端获取到所有的留⾔信息

接口定义:

1.发表留言接口:

请求:body为JSON格式.

请求路径:/message/publish

请求⽅式:POST

接⼝描述:校验数入格式是否正确

请求参数:

参数名类型
fromString
toString
sayString

响应数据:true:输入格式正确

                false:格式错误

前端代码:

<!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()"><!-- <div>A 对 B 说: hello</div> -->
</div><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
<!--提交信息-->function submit(){}
//    
</script>
</body></html>

后端代码:

定义信息对象MessageInfo类:

package com.model;import lombok.Data;@Data
public class MessageInfo {private String from;private String to;private String say;
}

 创建messageController类:

package com.springmvc.test;import ch.qos.logback.core.util.StringUtil;
import com.model.MessageInfo;
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 messageWallController {//留言集合:List<MessageInfo> messageInfos=new ArrayList<>();/***发表留言* @param messageInfo* @return*/@RequestMapping("/publish")public Boolean publish(MessageInfo messageInfo){
//        1.数据校验if(!StringUtils.hasLength(messageInfo.getFrom())|| !StringUtils.hasLength(messageInfo.getTo())|| !StringUtils.hasLength(messageInfo.getSay())){return false;}messageInfos.add(messageInfo);return true;}/*** 返回浏览信息* @return*/@RequestMapping("/getList")public List<MessageInfo> getList(){return messageInfos;}}

前端代码完善功能:


<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;}// 构造ajax请求$.ajax({url:"message/publish",type:"post",data:{from:from,to:to,say:say},success:function(result){if(result){//2. 构造节点var divE = "<div>"+from +"对" + to + "说:" + say+"</div>";//3. 把节点添加到页面上$(".container").append(divE);//4. 清空输入框的值$('#from').val("");$('#to').val("");$('#say').val("");}else{alert("输入信息格式有误!");}}});}
//     获取提交结果集合:$.ajax({url:"message/getList",type:"get",success:function(messageInfos){//将提交的所有信息进行字符串拼接:var finalHtml="";for(var messageInfo of messageInfos){finalHtml+="<div>"+messageInfo.from +"对" + messageInfo.to + "说:" + messageInfo.say+"</div>";}//     发送信息给后端$(".container").append(finalHtml);}});</script>

前后端参数对应关系:


http://www.ppmy.cn/devtools/161283.html

相关文章

Spring Boot 集成 T-io 实现客户端服务器通信

Spring Boot 集成 T-io 实现客户端服务器通信 本文详细介绍如何在 Spring Boot 项目中集成 T-io 框架&#xff0c;实现客户端与服务器之间的通信&#xff0c;并支持组聊、群聊和私聊功能。通过本文&#xff0c;您能够全面了解 T-io core 的使用方法&#xff0c;以及如何正确启…

ZLMediaKit Windows 编译指南

1 ZLMediaKit Windows 一般编译指南 ## 1. 环境准备 ### 1.1 必需工具 plaintext 1. Visual Studio 2019 或更高版本 2. CMake (3.15) 3. git 4. vcpkg (包管理器) ### 1.2 安装步骤 mermaid flowchart TB A[安装 Visual Studio] --> B[安装 CMake] B --> C…

OSPF基础知识总结

基本概念 协议类型:链路状态型IGP(内部网关协议),基于Dijkstra算法计算最短路径树。 协议号:IP层协议,协议号89。 特点:支持分层设计(区域划分)、快速收敛、无环路、支持VLSM/CIDR。 区域(Area) 骨干区域(Backbone Area):Area 0,所有非骨干区域必须直接或通过虚…

【Python】pypinyin-汉字拼音转换工具

文章目录 1. 主要功能2. 安装3. 常用API3.1 拼音风格3.2 核心API3.2.1 pypinyin.pinyin()3.2.2 pypinyin.lazy_pinyin()3.2.3 pypinyin.load_single_dict()3.2.4 pypinyin.load_phrases_dict()3.2.5 pypinyin.slug() 3.3 注册新的拼音风格 4. 基本用法4.1 库导入4.2 基本汉字转…

深入浅出Java虚拟机(JVM)核心原理

目录 一、JVM概述 1.1 大白话理解JVM 1.2 JVM架构 1.3 跨平台运行的本质 二、类加载器 1.1 类加载全过程 1.1.1 加载阶段 1.1.2 验证阶段 1.1.3 准备阶段 2.2 双亲委派机制 2.3 自定义类加载器 三、运行时数据区 3.1 堆内存结构 3.1.1 新生代参数优化 3.1.2 内存…

手机控制电脑远程关机

远程看看软件兼容iOS和Android设备&#xff0c;该软件除了能通过电脑远程关闭另一台电脑外&#xff0c;您还可以通过它在手机上远程关闭公司的电脑。您可以按照以下步骤进行操作以实现电脑远程关机&#xff1a; 步骤1.在手机应用商店搜索“远程看看”进行软件安装&#xff0c;…

1.24作业

1 pdf_converter ThinkPHP 5.x远程命令执行漏洞分析与复现 - 渗透测试中心 - 博客园 sindex/think%5Capp/invokefunction&functioncall_user_func_array&vars%5B0%5Dsystem&vars%5B1%5D%5B%5Dcat%2Fflag 2 三原色值0-255&#xff08;八位二进制&#xff09;&am…

Asp.Net 前后端分离项目——项目搭建

项目目录 MyDemoProject/ ├── BackendDemo/ # 后端项目目录 │ ├── Controllers/ # 控制器目录&#xff0c;存放 API 控制器 │ │ └── WeatherForecastController.cs │ ├── Models/ # 数据模型目录&#xff08;…