【JavaEE 进阶(二)】Spring MVC(下)

❣博主主页: 33的博客

▶️文章专栏分类:JavaEE◀️

🚚我的代码仓库: 33的代码仓库🚚

🫵🫵🫵关注我带你了解更多进阶知识

目录

1.前言

上一篇文章,我们已经讲了Spring MVC请求部分的内容,这篇文章继续讲解。

2.响应

2.1返回静态界面

在之前的代码中,我们都是以@RestController来注解一个类,通过这个注解那么就表明返回的内容都为数据,所以前⾯使⽤的@RestController 其实是返回的数据,如果我们想返回一个界面可以用@Controller,如果要返回数据@Controller+@ResponseBody =@RestController。

java 复制代码
@Controller
public class demo3 {
    @RequestMapping("/index")
    public String INDEX(){
        return "/index.html";
    }
}    

index.html内容

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>我是谁??</h1>
</body>
</html>

2.2返回数据

java 复制代码
@Controller
public class demo3 {
     @ResponseBody
    @RequestMapping("/date")
    public String DATA(){
        return "/index.html";
    }
}  

2.3返回HTML代码

java 复制代码
@Controller
public class demo3 {
  @ResponseBody
    @RequestMapping("/date2")
    public String DATA2(){
        return "<h1>我是谁??</h1>";
    }
}

3.综合练习

3.1计算器

java 复制代码
package com.example.test1;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/calc")
public class Caculation {
    @RequestMapping("/sum")
    public String CAL(Integer num1,Integer num2){
        Integer sum=num1+num2;
        return "计算结果:"+sum;
    }
}

HTML

html 复制代码
<!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>

结果

3.2用户登录

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({
            url:"/user/login",
            type: "post",
            data:{
                username: $("#userName").val(),
                password: $("#password").val()
            },
            // http响应成功
            success:function(result){
                console.log(result)

                if(result==true){
                    //页面跳转
                    location.href = "index.html";
                    // location.assign("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({
        url: "/user/index",
        type: "get",
        success:function(loginName){
            $("#loginUser").text(loginName);
        }
    });
</script>
</body>
</html>

后端代码:

java 复制代码
package com.example.test1;
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 UserController {
    @RequestMapping("/login")
    public boolean login(String username, String password, HttpSession session){        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            return false;
        }
        if("admin".equals(username)&&"admin".equals(password)){
            session.setAttribute("username",username);
            return true;
        }
       return false;
    }
    @RequestMapping("/index")
    public String getusername(@SessionAttribute("username") String username){
        return username;
    }
}

4.3留言板

java 复制代码
package com.example.test1;

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.LinkedList;
import java.util.List;

@RequestMapping("/message")
@RestController
public class MessageController {
    private List<MessageInfo> messageInfos=new ArrayList<>();
    @RequestMapping("/publish")
    public Boolean publish(MessageInfo messageInfo){
        System.out.println("接收到参数"+messageInfo);
        //参数检验
        if(!StringUtils.hasLength(messageInfo.getFrom())||!StringUtils.hasLength(messageInfo.getTo())||!StringUtils.hasLength(messageInfo.getSay())){
            return false;
        }
        messageInfos.add(messageInfo);
        return true;
    }
    @RequestMapping("/getlist")
    public List<MessageInfo> getList(){
        return messageInfos;
    }
}
java 复制代码
package com.example.test1;
import lombok.Data;
@Data
public class MessageInfo {
    private String from;
    private String to;
    private  String say;
}

HTML主要代码:

html 复制代码
<script>
    $.ajax({
        url: "/message/getlist",
        type: "get",
        success: function (messageInfos) {
            var finalHtml = "";
            for (var message of messageInfos) {
                finalHtml += '<div>' + message.from + ' 对 ' + message.to + ' 说: ' + message.message + '</div>';
            }
            $(".container").append(finalHtml);
        }
    });
    function submit() {
        console.log("发布留言");
        //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').val(),
                to: $('#to').val(),
                say: $('#say').val()
            },
            success: function (result) {
                if (result) {
                    console.log(result)
                    //2. 构造节点
                    var divE = "<div>" + from + "对" + to + "说:" + say + "</div>";
                    //3. 把节点添加到页面上
                    $(".container").append(divE);
                    //4. 清空输入框的值
                    $('#from').val("");
                    $('#to').val("");
                    $('#say').val("");
                }else{
                    alert("输入不合法");
                }
            }
        });

5.应用分层

通过上⾯的练习,我们学习了SpringMVC简单功能的开发,但是我们也发现了⼀些问题

⽬前我们程序的代码有点"杂乱",然⽽当前只是"⼀点点功能"的开发.如果我们把整个项⽬功能完成呢?代码会更加的"杂乱⽆章"。

在之前我们学过,MVC把整体的系统分成了model(模型)、View(视图)和Controller(控制器)三个层次,也就是将⽤⼾视图和业务处理隔离开,并且通过控制器连接起来,很好地实现了表现和逻辑的解耦,是⼀种标准的软件分层架构。

目前现在更主流的开发方式是前后端分离:"的⽅式,后端开发⼯程师不再需要关注前端的实现, 所以对于Java后端开发者,⼜有了⼀种新的分层架构:把整体架构分为表现层、业务逻辑层和数据层,这种方式使代码高内聚低耦合。这种分层⽅式也称之为"三层架构"。
表现层 :就是展⽰数据结果和接受⽤⼾指令的,是最靠近⽤⼾的⼀层;
业务逻辑层 :负责处理业务逻辑, ⾥⾯有复杂业务的具体实现;
数据层 : 负责存储和管理与应⽤程序相关的数据

我们一般把表现层命名为Controller,业务逻辑层命名为Service,数据层命名为Dao

6.企业规范

1.类名使用大驼峰的形式

2.⽅法名、参数名、成员变量、局部变量统,使⽤⼩驼峰⻛格

  1. 包名统⼀使⽤⼩写,点分隔符之间有且仅有一个⾃然语义的英语单词

7.总结

学习SpringMVC,其实就是学习各种Web开发需要⽤的到注解@RequestMapping:路由映射, @RequestParam:后端参数重命名, @RequestBody:接收JSON类型的参数, @PathVariable: 接收路径参数,@RequestPart: 上传⽂件,@ResponseBody:返回数据 等等...

下期预告:Spring IOC&DI

相关推荐
不能再留遗憾了6 小时前
【SpringCloud】Sentinel
spring·spring cloud·sentinel
whltaoin7 小时前
AI 超级智能体全栈项目阶段五:RAG 四大流程详解、最佳实践与调优(基于 Spring AI 实现)
java·人工智能·spring·rag·springai
心勤则明7 小时前
Spring AI 文档ETL实战:集成text-embedding-v4 与 Milvus
人工智能·spring·etl
艾菜籽7 小时前
Spring Web MVC入门补充1
java·后端·spring·mvc
艾菜籽10 小时前
Spring MVC入门补充2
java·spring·mvc
风兮w12 小时前
MVC、MVP和MVVM的区别
mvc
为java加瓦13 小时前
Spring 方法注入机制深度解析:Lookup与Replace Method原理与应用
java·数据库·spring
无名客014 小时前
SpringCloud中的网关(Gateway)的作用是什么?
spring·spring cloud·gateway
hrrrrb16 小时前
【Spring Security】Spring Security 概念
java·数据库·spring
小信丶16 小时前
Spring 中解决 “Could not autowire. There is more than one bean of type“ 错误
java·spring