今天我們來一個大練習,我們要實現一個登錄界面,登錄進去了先獲取到登錄人信息,可以選擇計算器和留言板兩個功能,另外我們是學后端的,對于前端我們會些基礎的就行了,知道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);}}})
?
我們點擊刷新之后還是有這些留言的: