Spring Web MVC————入門(3)

今天我們來一個大練習,我們要實現一個登錄界面,登錄進去了先獲取到登錄人信息,可以選擇計算器和留言板兩個功能,另外我們是學后端的,對于前端我們會些基礎的就行了,知道ajax怎么用,知道怎么關聯到后端的參數即可,對于那些漂亮的頁面,我們可以去Bootstrap找到各種各樣的模版。

1,定義接口文檔

我們后端程序員要學會根據接口文檔寫代碼,工作上就是這樣的,我們根據接口文檔來寫寫屬于我們那部分的代碼,我們現在來定義下面4個功能的接口文檔:

1,登錄接口文檔:

請求路徑:User/Login

請求方式:Post

請求參數:

參數名? ? ? ? ? ? ? ? 類型? ? ? ? ? ? ? ? 是否必須? ? ? ? ? ? ? ? 備注

userName? ? ? ? ? String? ? ? ? ? ? ? 是? ? ? ? ? ? ? ? ? ? ? ? ? ?需要校驗的第一個參數

password? ? ? ? ? ?String? ? ? ? ? ? ? 是? ? ? ? ? ? ? ? ? ? ? ? ? ?需要校驗的第二個參數

響應數據:

Content-Type:text/html

響應內容:

返回true? or? ?false

2,計算器接口文檔

請求路徑:Calc/Count

請求方式:Get

請求參數:

參數名? ? ? ? ? ? ? ? 類型? ? ? ? ? ? ? ? 是否必須? ? ? ? ? ? ? ? 備注

num1? ? ? ? ? ? ? ? ?Double? ? ? ? ? ? ?是? ? ? ? ? ? ? ? ? ? ? ? ? 參與計算的第一個參數

num2? ? ? ? ? ? ? ? ?Double? ? ? ? ? ? ?是? ? ? ? ? ? ? ? ? ? ? ? ? 參與計算的第二個參數

op? ? ? ? ? ? ? ? ? ? ? String? ? ? ? ? ? ? ?是? ? ? ? ? ? ? ? ? ? ? ? ? 運算符

響應數據:

Content-Type:text/html

響應內容:

返回計算結果Integer

3,留言板接口文檔

1)獲取內存歷史留言

請求路徑:Message/getList?

請求方式:get

請求參數:無

相應數據:

Content-Type:application/json

響應內容:

集合都是json,傳的對象

2)打印留言?

請求路徑:Message/publish

請求方式:get

請求參數:

MessageInfo messageinfo

對象中有String from String to String say

響應數據

Content-Type:text/html

響應內容:

json內容,如{"ok":0}

2,登錄功能實現

我們現在就來根據接口文檔來寫代碼:

@RequestMapping("/User")
@RestController
public class UserController {@RequestMapping("/Login")public boolean Login(String userName, String password, HttpServletRequest httpServletRequest){if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){return false;}if("admin".equals(userName) && "admin".equals(password)){httpServletRequest.setAttribute("userName",userName);return true;}return false;}
}

這里推薦大家去模版王找一些模版的前端代碼,我覺得很方便?

<!DOCTYPE html>
<html lang="zxx"><head><title>Hotair Login Form Responsive Widget Template</title><!-- Meta tag Keywords --><meta name="viewport" content="width=device-width, initial-scale=1"><meta charset="UTF-8"/><meta name="keywords"content="Hotair Login Form Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design"/><!-- //Meta tag Keywords --><link href="https://fonts.googleapis.com/css2?family=Noto+Serif+JP:wght@400;600;700;900&display=swap"rel="stylesheet"><!--/Style-CSS --><link rel="stylesheet" href="css/style.css" type="text/css" media="all"/><!--//Style-CSS --><link rel="stylesheet" href="css/font-awesome.min.css" type="text/css" media="all"></head><body><!-- form section start -->
<section class="w3l-hotair-form"><h1>Hotair Log In Form</h1><div class="container"><!-- /form --><div class="workinghny-form-grid"><div class="main-hotair"><div class="alert-close"><span class="fa fa-close"></span></div><div class="content-wthree"><h2>Log In</h2><p>To Your Account</p><form action="#" method="post"><input type="text" class="text" name="userName" placeholder="User Name" required=""id="userName"><input type="password" class="password" name="password" placeholder="User Password" required=""id="password"><button class="btn" type="submit" onclick="heihei()">Log In</button></form></div><div class="w3l_form align-self"><div class="left_grid_info"></div></div></div></div><!-- //form --></div><!-- copyright--><div class="copyright text-center"><p class="copy-footer-29">? 2020 Hotair Log In Form. All rights reserved | <a target="_blank"href="http://www.mobanwang.com/"title="網頁模板">網頁模板</a></p></div><!-- //copyright-->
</section>
<!-- //form section start --><script src="js/jquery.min.js"></script>
<script>$(document).ready(function (c) {$('.alert-close').on('click', function (c) {$('.main-hotair').fadeOut('slow', function (c) {$('.main-hotair').remove();});});});function heihei() {$.ajax({type: "post",url: "User/Login",data: {userName: $("#userName").val(),password: $("#password").val()},success: function (result) {if (result == false) {alert("用戶名或者密碼出錯")} else {location.href = "calc.html"}}})}
</script></body></html>

我把html的文件放上去了,css,js都沒有,大家去模版王找就行,之后,在Script中關聯好后端傳來的數據就行了;?

來看看效果:

密碼正確則成功跳轉,

3,跳轉界面實現

這塊就是純前端的內容了,對點擊的框框進行頁面的跳轉,

<!DOCTYPE html>
<html lang="zxx"><head><title>Hotair Login Form Responsive Widget Template</title><!-- Meta tag Keywords --><meta name="viewport" content="width=device-width, initial-scale=1"><meta charset="UTF-8"/><meta name="keywords"content="Hotair Login Form Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design"/><!-- //Meta tag Keywords --><link href="https://fonts.googleapis.com/css2?family=Noto+Serif+JP:wght@400;600;700;900&display=swap"rel="stylesheet"><!--/Style-CSS --><link rel="stylesheet" href="css/style.css" type="text/css" media="all"/><!--//Style-CSS --><link rel="stylesheet" href="css/font-awesome.min.css" type="text/css" media="all"></head><body><!-- form section start -->
<section class="w3l-hotair-form"><h1>小 工 具</h1><div class="container"><!-- /form --><div class="workinghny-form-grid"><div class="main-hotair"><div class="alert-close"><span class="fa fa-close"></span></div><div class="content-wthree"><h2>Log In</h2><p>To Your Account</p><form action="#" method="post"><input type="text" class="text" name="userName" placeholder="User Name" required=""id="userName"><input type="password" class="password" name="password" placeholder="User Password" required=""id="password"><button class="btn" type="submit" onclick="heihei()">Log In</button></form></div><div class="w3l_form align-self"><div class="left_grid_info"></div></div></div></div><!-- //form --></div><!-- copyright--><!-- //copyright-->
</section>
<!-- //form section start --><script src="js/jquery.min.js"></script>
<script>$(document).ready(function (c) {$('.alert-close').on('click', function (c) {$('.main-hotair').fadeOut('slow', function (c) {$('.main-hotair').remove();});});});function heihei() {$.ajax({type: "post",url: "User/Login",data: {userName: $("#userName").val(),password: $("#password").val()},success: function (result) {if (result == false) {alert("用戶名或者密碼出錯")location.href = "index.html"} else {location.href = "choose.html"}}})}
</script></body></html>

4,計算器功能實現

我們計算器呢就先不使用模版了,用模版的話在前端中就都寫好了,沒我們什么事了,我們自己來!

先來看后端代碼:

@RequestMapping("/Calc")
@RestController
public class CalcController {@RequestMapping("/count")public Double count(Double num1,Double num2,String op){Double num=0.0;if(num1==null || num2==null){return null;} else {if("+".equals(op)){num=num1+num2;} else if ("-".equals(op)) {num=num1-num2;} else if ("*".equals(op)){num=num1*num2;} else if ("/".equals(op)) {if(num1==0){return null;}num=num1/num2;} else if ("%".equals(op)) {num=num1%num2;}}System.out.println(num);return num;}}

前端的:

?

<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><h1>計算器</h1><button type="button" onclick="clean()">AC</button><br>數字1:<input name="num1" type="text" id="num1"><br>數字2:<input name="num2" type="text" id="num2"><br><select id="op" name="op1"><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/" selected>/</option><option value="%">%</option></select><br><span id="result"></span><br><button type="submit" onclick="count()">計算結果</button><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>function count(){$.ajax({type:"get",url:"Calc/count",data:{num1:$("#num1").val(),num2:$("#num2").val(),op:$("#op").val()},success:function (result) {if(result==null){alert("輸入參數有問題呀")}else {$("#result").html(result);}}})}function clean() {$("#num1").val("")$("#num2").val("")$("#result").html("")}
</script>
</body></html>

5,留言板功能實現

@Data
public class MessageInfo {private String from;private String to;private String say;
}

先來publish:

這里我們使用鏈表,這個是在內存中的,我們看publish方法,我們如果想要傳入json數據給后端我們要使用produces,這樣messageinfo對象就能接收到json格式的數據轉化成對應的對象中的內容,之后我們想要輸出json,我們就要使用produces,這個之前講過,可以指定我們返回的類型;


@RequestMapping("/Message")
@RestController
public class MessageController {List<MessageInfo> arrayList = new ArrayList<>();@RequestMapping(value = "/publish",produces = "application/json")public String publish(@RequestBody MessageInfo messageInfo){if (messageInfo==null){return "{\"ok\":0}";}if(messageInfo.getTo()!=null || messageInfo.getFrom()!=null ||messageInfo.getSay()!=null){arrayList.add(messageInfo);return "{\"ok\":1}";}return "{\"ok\":0}";}}
    <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>

在點擊按鈕后就會調用這個方法,重點!我們接收要使用Post方法接收JSON請求體?,

ContentType:"application/json"表明我們傳入的JSON數據會轉化為對象,所以result就是對象了,這個data:JSON.stringify就是把data對象轉變為json為啥呢,因為參數類型是json嗎,所以我們就要前端上也寫類型為json,

 function submit() {var from1 = $("#from").val();var to1 = $("#to").val();var say1 = $("#say").val();var data1 = {from : $('#from').val(),to : $('#to').val(),say : $('#say').val(),}$.ajax({type:"post",url:"/Message/publish",contentType: "application/json",data: JSON.stringify(data1),success: function (result) {if(result.ok==0){alert("留言失敗")}else{//2. 構造節點var divE = "<div>"+ from1 +"對" + to1 + "說:" + say1+"</div>";//3. 把節點添加到頁面上$(".container").append(divE);//4. 清空輸入框的值$('#from').val("");$('#to').val("");$('#say').val("");}}})}

?

下面來getLIst方法,這個方法的主要目的就是我們刷新之后自動加載我們之前寫的內容,容器是存活在內存中,所以關機或者長時間不使用都會發生錯誤的;

?后端代碼:

    @RequestMapping("/getList")public List<MessageInfo> getList(){return arrayList;}

?前端代碼:ajax:

   $.ajax({type: "get",url: "/Message/getList",success: function (result) {if(result!=null && result.length>0){var html1=" ";for( var a of result){html1 += "<div>"+a.from +"對" + a.to + "說:" + a.say+"</div>";}$(".container").append(html1);}}})

?

我們點擊刷新之后還是有這些留言的:

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/83657.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/83657.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/83657.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

PhpStudy | PhpStudy 工具安裝 —— Windows 系統安裝 PhpStudy

&#x1f31f;想了解這個工具的其它相關筆記&#xff1f;看看這個&#xff1a;[網安工具] 服務器環境配置工具 —— PhpStudy 使用手冊 筆者備注&#xff1a;Windows 中安裝 PhpStudy 屬于傻瓜式安裝&#xff0c;本文只是為了體系完善而發。 在前面的章節中&#xff0c;筆者簡…

K230 ISP:一種新的白平衡標定方法

第一次遇見需要利用光譜響應曲線進行白平衡標定的方法。很好奇是如何利用光譜響應曲線進行白平衡標定的。 參考資料參考&#xff1a;K230 ISP圖像調優指南 K230 介紹 嘉楠科技 Kendryte 系列 AIoT 芯片中的最新一代 AIoT SoC K230 芯片采用全新的多核異構單元加速計算架構&a…

通俗解釋Transformer在處理序列問題高效的原因(個人理解)

Transformer出現的背景 CNN 的全局關聯缺陷卷積神經網絡&#xff08;CNN&#xff09;通過多層堆疊擴大感受野&#xff0c;但在自然語言處理中存在本質局限&#xff1a; 局部操作的語義割裂&#xff1a;每個卷積核僅處理固定窗口&#xff08;如 3-5 詞&#xff09;&#xff0c;…

Java 多線程基礎:Thread 類核心用法詳解

一、線程創建 1. 繼承 Thread 類&#xff08;傳統寫法&#xff09; class MyThread extends Thread { Override public void run() { System.out.println("線程執行"); } } // 使用示例 MyThread t new MyThread(); t.start(); 缺點&#xff1a;Java 單…

Django 中時區的理解

背景 設置時區為北京時間 TIME_ZONE ‘Asia/Shanghai’ # 啟用時區支持 USE_TZ True 這樣設置的作用 前端 &#xff08;實際上前端el-date-picker 顯示的是當地時區的時間&#xff09; Element組件轉換后&#xff0c;我們是東八區&#xff0c;前端傳給后端的時間為&…

C# 深入理解類(成員常量)

成員常量 成員常量類似前一章所述的局部常量&#xff0c;只是它們被聲明在類聲明中而不是方法內&#xff0c;如下面的 示例&#xff1a; 與局部常量類似&#xff0c;用于初始化成員肯量的值在編譯時必須是可計算的&#xff0c;而且通常是一個預定 義簡單類型或由它們組成的表達…

【深度學習】#12 計算機視覺

主要參考學習資料&#xff1a; 《動手學深度學習》阿斯頓張 等 著 【動手學深度學習 PyTorch版】嗶哩嗶哩跟李沐學AI 目錄 目標檢測錨框交并比&#xff08;IoU&#xff09;錨框標注真實邊界框分配偏移量計算損失函數 非極大值抑制預測 多尺度目標檢測單發多框檢測&#xff08;S…

MCP實戰:在扣子空間用扣子工作流MCP,一句話生成兒童故事rap視頻

扣子最近迎來重要更新&#xff0c;支持將扣子工作流一鍵發布成MCP&#xff0c;在扣子空間里使用。 這個功能非常有用&#xff0c;因為我有很多業務工作流是在扣子平臺上做的&#xff0c;兩者打通之后&#xff0c;就可以在扣子空間里直接通過對話方式調用扣子工作流了&#xff0…

Redis學習打卡-Day3-分布式ID生成策略、分布式鎖

分布式 ID 當單機 MySQL 已經無法支撐系統的數據量時&#xff0c;就需要進行分庫分表&#xff08;推薦 Sharding-JDBC&#xff09;。在分庫之后&#xff0c; 數據遍布在不同服務器上的數據庫&#xff0c;數據庫的自增主鍵已經沒辦法滿足生成的主鍵全局唯一了。這個時候就需要生…

LabVIEW光譜信號仿真與數據處理

在光譜分析領域&#xff0c;LabVIEW 憑借其圖形化編程、豐富函數庫及強大數據處理能力&#xff0c;成為高效工具。本案例將介紹如何利用 LabVIEW 仿真光譜信號&#xff0c;并對實際采集的光譜數據進行處理&#xff0c;涵蓋信號生成、數據采集、濾波、分析及顯示等環節。 ? 一…

nginx相關面試題30道

一、基礎概念與核心特性 1. 什么是 Nginx&#xff1f;它的主要用途有哪些&#xff1f; 答案&#xff1a; Nginx 是一款高性能的開源 Web 服務器、反向代理服務器及負載均衡器&#xff0c;基于事件驅動的異步非阻塞架構&#xff0c;擅長處理高并發場景。 主要用途&#xff1a;…

數據庫實驗報告 數據定義操作 3

實驗報告&#xff08;第3次&#xff09; 實驗名稱 數據定義操作 實驗時間 10月12日1-2節 一、實驗內容 1、本次實驗是用sql語句創建庫和表&#xff0c;語句是固定的&#xff0c;要求熟記這些sql語句。 二、源程序及主…

霍夫圓變換全面解析(OpenCV)

文章目錄 一、霍夫圓變換基礎1.1 霍夫圓變換概述1.2 圓的數學表達與參數化 二、霍夫圓變換算法實現2.1 標準霍夫圓變換算法流程2.2 參數空間的表示與優化 三、關鍵參數解析3.1 OpenCV中的HoughCircles參數3.2 參數調優策略 四、Python與OpenCV實現參考4.1 基本實現代碼4.2 改進…

記錄一次修改nacos安全問題導致服務調用出現404

1、nacos默認值修改 nacos.core.auth.plugin.nacos.token.secret.key**** nacos.core.auth.server.identity.key******** nacos.core.auth.server.identity.value************ 重啟nacos, 這時候微服務的token認證會立即失效&#xff0c;等待自動重連認證或者手動重啟服務 2、…

Python面試總結

hello&#xff0c;大家好&#xff0c;我是potato&#xff0c;我總結一下最近的面試遇到的問題~ 1.Python開發&#xff08;軟通動力&#xff09; 自我介紹主要問了項目(YOLOv11)項目遇到的難點和解決方法is&#xff0c;列表和元組的區別Python多線程有什么問題&#xff1f;Pyt…

5.18 day24

知識點回顧&#xff1a; 元組可迭代對象os模塊 作業&#xff1a;對自己電腦的不同文件夾利用今天學到的知識操作下&#xff0c;理解下os路徑。 元組 元組的特點&#xff1a; 有序&#xff0c;可以重復&#xff0c;這一點和列表一樣 元組中的元素不能修改&#xff0c;這一點…

Uniapp中小程序調用騰訊地圖(獲取定位地址)

1、先配置權限&#xff1a; 這是上圖的代碼&#xff1a; "permission": { "scope.userLocation": { "desc": "你的位置信息將用于小程序位置接口的效果展示" } } 第二步&#xff1a;寫代碼&#xff1a; //下面是uniapp的模版代碼 主…

寫spark程序數據計算( 數據庫的計算,求和,匯總之類的)連接mysql數據庫,寫入計算結果

1. 添加依賴 在項目的 pom.xml&#xff08;Maven&#xff09;中添加以下依賴&#xff1a; xml <!-- Spark SQL --> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-sql_2.12</artifactId> <version>3.3.0…

nginx服務器實驗

1.實驗要求 1&#xff09;在Nginx服務器上搭建LNMP服務&#xff0c;并且能夠對外提供Discuz論壇服務。 在Web1、Web2服務器上搭建Tomcat 服務。 2&#xff09;為nginx服務配置虛擬主機&#xff0c;新增兩個域名 www.kgc.com 和 www.benet.com&#xff0c;使用http://www.kgc.…

Spring Boot 與 RabbitMQ 的深度集成實踐(一)

引言 ** 在當今的分布式系統架構中&#xff0c;隨著業務復雜度的不斷提升以及系統規模的持續擴張&#xff0c;如何實現系統組件之間高效、可靠的通信成為了關鍵問題。消息隊列作為一種重要的中間件技術&#xff0c;應運而生并發揮著舉足輕重的作用。 消息隊列的核心價值在于其…