0


【Spring MVC篇】简单案例分析

个人主页:兜里有颗棉花糖
欢迎 点赞👍 收藏✨ 留言✉ 加关注💓本文由 兜里有颗棉花糖 原创
收录于专栏【Spring MVC】
本专栏旨在分享学习Spring MVC的一点学习心得,欢迎大家在评论区交流讨论💌
在这里插入图片描述

目录

一、加法计算器

前端代码:

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><formaction="/calc/sum"method="post"><h1>计算器</h1>
        数字1:<inputname="num1"type="text"><br>
        数字2:<inputname="num2"type="text"><br><inputtype="submit"value=" 点击相加 "></form></body></html>

后端代码:

packageorg.example.demo1.demos.web.controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RequestMapping("/calc")@RestControllerpublicclassCalcController{@RequestMapping("/sum")publicStringsum(Integer num1,Integer num2){Integer sum = num1 + num2;return"计算结果为:"+ sum;}}

运行结果:
在这里插入图片描述
在这里插入图片描述

二、登录页面

前端两个文件(

login.html

index.html

),后端一个文件(

UserController.java

)。

后端代码如下:

packageorg.example.demo1.demos.web.controller;importorg.springframework.util.StringUtils;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importjavax.servlet.http.HttpSession;@RequestMapping("/user")@RestControllerpublicclassUserController{@RequestMapping("/login")publicBooleanlogin(String userName,String password,HttpSession session){// 校验参数的合法性if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password))returnfalse;// 进行用户名和密码的校验if("admin".equals(userName)&&"admin".equals(password)){
            session.setAttribute("username","admin");returntrue;}returnfalse;}@RequestMapping("/getUserInfo")publicStringgetUserInfo(HttpSession session){// 从session中获取session用户String userName =(String) session.getAttribute("username");return userName;}}

login.html

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>登录页面</title></head><body><h1>用户登录</h1>
用户名:<inputname="userName"type="text"id="userName"><br>
密码:<inputname="password"type="password"id="password"><br><inputtype="button"value="登录"onclick="login()"><scriptsrc="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>functionlogin(){// console.log("登录...")
        $.ajax({url:"/user/login",type:"post",data:{"userName":$("#userName").val(),"password":$("#password").val()},success:function(result){if(result){
                    location.href ="/index.html";// 方式一// location.assign(); 方式二}else{alert("密码错误");}}})}</script></body></html>

index.html

<!doctypehtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><metahttp-equiv="X-UA-Compatible"content="ie=edge"><title>用户登录首页</title></head><body>
登录人: <spanid="loginUser"></span><scriptsrc="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>// 页面加载时,就去调用后端请求
    $.ajax({url:"/user/getUserInfo",type:"get",success:function(username){$("#loginUser").text(username);}})</script></body></html>

三、留言板

后端接口定义:
**1.提交留言(

/message/publish

):**
参数:MessageInfo(from,to,message)
返回结果:true/false
**2.查看所有留言(

/message/getMessageList

):**
参数:无
**返回结果:

List<MessageInfo>

**

前端代码:

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="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><divclass="container"><h1>留言板</h1><pclass="grey">输入后点击提交, 会将信息显示下方空白处</p><divclass="row"><span>谁:</span><inputtype="text"name=""id="from"></div><divclass="row"><span>对谁:</span><inputtype="text"name=""id="to"></div><divclass="row"><span>说什么:</span><inputtype="text"name=""id="say"></div><inputtype="button"value="提交"id="submit"onclick="submit()"><!-- <div>A 对 B 说: hello</div> --></div><scriptsrc="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>// 页面加载时请求后端获取留言列表
    $.ajax({url:"/message/getMessageInfo",type:"get",success:function(messages){for(var m of messages){//2. 构造节点(拼接节点的html)var divE ="<div>"+m.from +"对"+ m.to +"说:"+ m.message+"</div>";//3. 把节点添加到页面上$(".container").append(divE);}}});functionsubmit(){//1. 获取留言的内容var from =$('#from').val();var to =$('#to').val();var say =$('#say').val();if(from==''|| to ==''|| say ==''){return;}// 提交留言
        $.ajax({url:"/message/publish",type:"post",data:{"from":from,"to":to,"message":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("留言发布失败")}}});}</script></body></html>

后端代码:

packageorg.example.demo1.demos.web.controller;importorg.springframework.util.StringUtils;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importjava.util.ArrayList;importjava.util.List;@RequestMapping("/message")@RestControllerpublicclassMessageController{privateList<MessageInfo> messageInfos =newArrayList<>();@RequestMapping("/publish")publicBooleanpublicMessage(MessageInfo messageInfo){if(!StringUtils.hasLength(messageInfo.getMessage())||!StringUtils.hasLength(messageInfo.getFrom())||!StringUtils.hasLength((messageInfo.getTo()))){returnfalse;}
        messageInfos.add(messageInfo);returntrue;}@RequestMapping("/getMessageInfo")publicList<MessageInfo>getMessageInfo(){return messageInfos;}}

效果演示:

在这里插入图片描述

好了,以上就是本文的全部内容了。希望各位友友可以一键三连哈!!!

在这里插入图片描述

标签: spring mvc java

本文转载自: https://blog.csdn.net/m0_74352571/article/details/136121571
版权归原作者 兜里有颗棉花糖 所有, 如有侵权,请联系我们删除。

“【Spring MVC篇】简单案例分析”的评论:

还没有评论