当前位置: 首页 > news >正文

【Java项目实战】牛客网论坛项目1 - Spring入门与初识SpringMVC

目录

    • Spring 入门
      • SpringInitializr
      • ApplicationContextAware
      • Controller
      • DAO
      • DAO 名称索引
      • Service
      • Config
      • 自动装配
    • 初识 SpringMVC
      • Http 请求
      • GET
      • POST
      • HTML 渲染
      • 响应 JSON 数据

Spring 入门

SpringInitializr

IDEA 专业版自带的功能,也可以直接搜索对应网站,通过网站生成包后导入 IDEA 中使用

下面是初始化的参数:

  • 选用 SpringBoot2.7.15
  • 导入依赖 Web、DevTools、Thymeleaf

之后等待构建完毕即可


ApplicationContextAware

在测试函数中使用 ApplicationContextAware 来获取应用上下文

package com.zhiller.community.zhillercommunity;import com.zhiller.community.zhillercommunity.dao.AlphaDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;@SpringBootTest
// @SpringBootTest 是 Spring Boot 提供的测试注解,用于表示这是一个 Spring Boot 的测试类。
// 它会自动加载 Spring Boot 的配置,并启动 Spring 容器,以便进行集成测试。
@ContextConfiguration(classes = ZhillerCommunityApplication.class)
// @ContextConfiguration 用于指定 Spring 容器的配置信息。
// 这里使用 ZhillerCommunityApplication.class 表示使用该类所在的包作为配置信息。
class ZhillerCommunityApplicationTests implements ApplicationContextAware {private ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}// 实现 ApplicationContextAware 接口的方法,用于获取 Spring 应用上下文对象。}

Controller

创建 controller 文件

package com.zhiller.community.zhillercommunity.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
@RequestMapping("/alpha")
public class AlphaController {// 处理"/alpha/helloworld"请求,返回字符串响应@RequestMapping("/helloworld")// @ResponseBody注解表示将方法的返回值直接作为响应体返回,而不是将其解析为视图名称@ResponseBodypublic String hello(){return "shit man!";}
}

运行 Application,之后打开浏览器,输入 localhost:10086/alpha/helloworld 获取请求结果


DAO

主应用包下新建两个文件,分别是 DAO 接口以及其对应实现类

代码清单:AlphaDao.java

package com.zhiller.community.zhillercommunity.dao;public interface AlphaDao {String select();
}

代码清单:AlphaDaoImpl.java

package com.zhiller.community.zhillercommunity.dao;import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;@Repository
// @Repository 是 Spring 提供的注解,用于表示该类是一个数据访问对象(DAO)。
// 它会被 Spring 自动扫描并将其注册为 Spring 容器中的一个 Bean。
@Primary
// @Primary 是 Spring 提供的注解,用于表示当存在多个同一类型的 Bean 时,优先选择被标记为 @Primary 的 Bean。
// 在自动装配时,如果没有明确指定要注入哪个 Bean,将会选择被标记为 @Primary 的 Bean。
public class AlphaDaoImpl implements AlphaDao {// AlphaDao 是一个接口,AlphaDaoImpl 类实现了该接口。@Overridepublic String select() {return "hibernate";}// 实现了 AlphaDao 接口中的 select() 方法,返回字符串 "hibernate"。
}

最后在主测试类中对这个 DAO 进行测试

@SpringBootTest
@ContextConfiguration(classes = ZhillerCommunityApplication.class)
class ZhillerCommunityApplicationTests implements ApplicationContextAware {private ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}@Testpublic void testContext(){System.out.println(applicationContext);AlphaDao alphaDao = applicationContext.getBean(AlphaDao.class);System.out.println(alphaDao.select());}
}

DAO 名称索引

对 DAO 实现类的注解@Repository添加一段字符串描述,即可直接通过该字符串获取该 DAO

@Repository("alpha_hibernate")
@Primary
public class AlphaDaoImpl implements AlphaDao {@Overridepublic String select() {return "hibernate";}
}

故对应的测试类可以这么写

@Test
public void testContext(){System.out.println(applicationContext);AlphaDao alphaDao = applicationContext.getBean("alpha_hibernate",AlphaDao.class);System.out.println(alphaDao.select());
}

Service

创建 service 包,下含一个 Service 类

代码清单 AlphaService.java

package com.zhiller.community.zhillercommunity.service;import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;@Service
// @Service 是 Spring 提供的注解,用于表示该类是一个服务类。
// 它会被 Spring 自动扫描并将其注册为 Spring 容器中的一个 Bean。
@Scope("prototype")
// @Scope 是 Spring 提供的注解,用于指定 Bean 的作用域。
// 这里的 "prototype" 表示每次请求该 Bean 都会创建一个新的实例。
public class AlphaService {public AlphaService() {System.out.println("实例化service");// 在构造函数中打印一条实例化的信息。}@PostConstruct// @PostConstruct 是 Java 的注解,用于指定在构造函数执行后执行的方法。// 在该方法上添加 @PostConstruct 注解后,Spring 会在构造函数执行完毕后调用该方法。public void init(){System.out.println("初始化service");// 在 init() 方法中打印一条初始化的信息。}@PreDestroy// @PreDestroy 是 Java 的注解,用于指定在 Bean 销毁之前执行的方法。// 在该方法上添加 @PreDestroy 注解后,Spring 会在销毁 Bean 之前调用该方法。public void destory(){System.out.println("销毁service");// 在 destory() 方法中打印一条销毁的信息。}
}

对应的测试文件这里不在给出,使用方式和 DAO 完全一致


Config

配置 Config 文件和 service、dao 如出一辙

代码清单 AlphaConfig.java

package com.zhiller.community.zhillercommunity.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.text.SimpleDateFormat;@Configuration
public class AlphaConfig {@Beanpublic SimpleDateFormat simpleDateFormat(){return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}
}

自动装配

springboot 提供了自动装配,我们无需获取 applicationcontext 就可以直接使用对应的实例了

// 测试类中使用@Autowired和@Qualifier注解来自动装配依赖关系
@Autowired
// @Qualifier("alpha_hibernate")用于指定要注入的alphaDao的Bean名称为"alpha_hibernate"
@Qualifier("alpha_hibernate")
private AlphaDao alphaDao;@Autowired
private AlphaService alphaService;

初识 SpringMVC

Http 请求

AlphaService.java 修改代码

添加一个 http 请求,并通过该请求获取指定参数

package com.zhiller.community.zhillercommunity.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;@Controller
@RequestMapping("/alpha")
public class AlphaController {/*** 处理映射到 "/alpha/http" 路径的请求* 打印请求的 HTTP 方法、请求头信息和请求参数* 设置响应内容类型为 text/html;charset=utf-8* 获取响应输出流并进行异常处理*/@RequestMapping("/http")public void http(HttpServletRequest request, HttpServletResponse response) {// 打印请求的 HTTP 方法System.out.println(request.getMethod());// 获取所有请求头的名称并打印Enumeration<String> enumeration = request.getHeaderNames();while (enumeration.hasMoreElements()) {String name = enumeration.nextElement();String value = request.getHeader(name);System.out.println(name + ":" + value);}// 打印请求参数 "code"System.out.println(request.getParameter("code"));// 设置响应内容类型为 text/html;charset=utf-8response.setContentType("text/html;charset=utf-8");try (PrintWriter writer = response.getWriter();){writer.write("<h1>zhiller labs</h1>");}catch(IOException e) {e.printStackTrace();}}
}

GET

package com.zhiller.community.zhillercommunity.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
@RequestMapping("/alpha")
public class AlphaController {/*** 处理映射到 "/alpha/getage" 路径的 GET 请求* 接受名为 "age" 的请求参数,如果参数不存在则使用默认值 1* 打印参数值并返回字符串 "age"*/@GetMapping("/getage")@ResponseBodypublic String getAge(@RequestParam(name = "age", required = false, defaultValue = "1") int age) {System.out.println(age);return "age";}/*** 处理映射到 "/alpha/getid/{id}" 路径的 GET 请求* 接受路径变量 "id"* 打印路径变量值并返回字符串 "get the id"*/@GetMapping("/getid/{id}")@ResponseBodypublic String getId(@PathVariable("id") int id) {System.out.println(id);return "get the id";}
}

POST

随便写一个登录页面,存放位置:resource/static/html/student.html

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><title>oh my god</title></head><body><div class="main">look this big shit!!!</div><!-- 要注意这里的请求方法为POST,请求url要和springboot里面定义的一致 --><formmethod="post"action="/alpha/student"><p>姓名:<inputtype="text"name="name"placeholder="请输入您的姓名"/></p><p>密码:<inputtype="password"name="pwd"placeholder="******"/></p><p><inputtype="submit"value="保存"/></p></form></body>
</html><style>.main {font-size: large;font-weight: bold;}
</style>

然后就是我们的 controller 方法了

@PostMapping("/student")
public void postStudent(String name, String password) {System.out.println(name);System.out.println(password);return;
}

HTML 渲染

thymeleaf 的作用是帮助我们后端渲染简单的前端界面

但是很明显,在现在前后端分类的大趋势下,这玩意就和当年的 JSP 一样没有前景

建议不学


响应 JSON 数据

package com.zhiller.community.zhillercommunity.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.HashMap;
import java.util.Map;@Controller
@RequestMapping("/alpha")
public class AlphaController {/*** 处理映射到 "/alpha/emp" 路径的 GET 请求* 返回一个包含员工信息的 Map 对象*/@GetMapping("/emp")@ResponseBodypublic Map<String, Object> getEmp() {// 创建一个 Map 对象用于存储员工信息Map<String, Object> map = new HashMap<>();map.put("name", "张三");map.put("age", 123);return map;}
}

相关文章:

【Java项目实战】牛客网论坛项目1 - Spring入门与初识SpringMVC

目录 Spring 入门SpringInitializrApplicationContextAwareControllerDAODAO 名称索引ServiceConfig自动装配 初识 SpringMVCHttp 请求GETPOSTHTML 渲染响应 JSON 数据 Spring 入门 SpringInitializr IDEA 专业版自带的功能&#xff0c;也可以直接搜索对应网站&#xff0c;通…...

Gurobi使用(一)——操作指南(转自知乎)

好像还是要学一下Gurobi如何使用的&#xff0c;不然这代码着实有点抽象了 一、入门操作 一般来说&#xff0c;求解一个数学规划模型的时候&#xff0c;通常会按照如下步骤解决问题: 设置变量---addVar()。 更新变量空间---update()。 设定目标函数---setObjective()。 设定约…...

计算机网络的故事——简单的HTTP协议

简单的HTTP协议 文章目录 简单的HTTP协议一、简单的HTTP协议 一、简单的HTTP协议 HTTP是不保存状态的协议&#xff0c;为了实现保存状态功能于是引入了Cookie技术。 method: get:获取资源 post:传输实体主体 put:传输文件 head:获取报文首部&#xff0c;用于确认URI的有效性以…...

新能源商用车软件开发设计规范

目 录 前 言.............................................................................................................. 1 1 范围............................................................................................................... 2 2 规范性…...

Json“牵手”当当网商品详情数据方法,当当商品详情API接口,当当API申请指南

当当网是知名的综合性网上购物商城&#xff0c;由国内著名出版机构科文公司、美国老虎基金、美国IDG集团、卢森堡剑桥集团、亚洲创业投资基金&#xff08;原名软银中国创业基金&#xff09;共同投资成立1。 当当网从1999年11月正式开通&#xff0c;已从早期的网上卖书拓展到网…...

lazarus开发界面程序用线程显示进度条

lazarus开发界面程序用线程显示进度条&#xff0c;效果更好&#xff0c;以前没有另外显示线程&#xff0c;遇到上传文件或其他较长时间操作&#xff0c;界面就卡在那里&#xff0c;体验不好&#xff0c;现在另外启动线程操作&#xff0c;主界面就不至于卡在那里。 首先在主界面…...

解决VSCode下载速度特别慢的问题

一、下载VSCode 1.打开VSCode官网 https://code.visualstudio.com 2.download下载 3.下载特别慢 二、解决VSCode下载速度特别慢 1.单击右下角全部显示 我是用chrome浏览器&#xff0c;点击右下角的全部显示按钮&#xff0c;可以跳转到下载内容页面。 如果你是用其他浏览器…...

国家矿山安全监察局关于露天矿山边坡监测系统建设及预警响应要求

矿山是人类社会发展的物资基础&#xff0c;也是国民经济的重要组成部分。随着我国经济的快速增长&#xff0c;矿山开发步伐加快&#xff0c;使得边坡问题日益严重&#xff0c;影响了矿山的安全生产。为有效防范遏制矿山重特大事故发生&#xff0c;国家矿山安全监察局在8月30日发…...

前端使用elementui开发后台管理系统的常用功能(持续更新)

前言&#xff1a;本次的文章完全是自己开发中遇到的一些问题&#xff0c;经过不断的修改终于完成的一些功能&#xff0c;当个快捷的查看手册吧~ elementui开发后台管理系统常用功能 高级筛选的封装elementui的表格elementui的表格实现跨页多选回显elementui的表单elementui的日…...

中东 Shopify 如何使用 Bytebase 构建一站式数据库开发工作流

公司简介 Salla 是一家 2016 年成立&#xff0c;位于沙特麦加的自建站电商平台。 作为中东 Shopify&#xff0c;其最大的特点是支持阿拉伯语建站&#xff0c;并且提供更多适应中东地区特点的本地化服务。截止目前&#xff0c;已有 47,000 家店铺入驻 Salla&#xff0c;商品销售…...

谷歌Chrome庆祝15周年,推出全新设计!了解最新信息!

谷歌浏览器本月将满15岁&#xff0c;为了纪念这一时刻&#xff0c;它正在进行改造和升级。 这一点意义重大&#xff0c;因为Chrome在全球有数十亿人使用&#xff0c;因此谷歌所做的每一项改变都会对互联网以及这些人与互联网的互动方式产生巨大影响。即使你不使用Chrome或不关…...

解决Oracle SQL语句性能问题——SQL语句改写(分析函数、with as、union及or)

1. 正确使用分析函数 分析函数最早出现于Oracle 8i版本中,并在后续版本中不断得以增强。正确的使用分析函数,不但能非常方便的实现某些功能,而且,在某些场景中,还可以大幅提升SQL语句的性能。因此,为了简化应用实现逻辑或解决相关SQL语句性能问题,有时我们需要利用分析…...

Linux之SELinux

目录 概述 定义 作用 SELinux与传统的权限区别 SELinux工作原理 名词解释 主体&#xff08;Subject&#xff09; 目标&#xff08;Object&#xff09; 策略&#xff08;Policy&#xff09; 安全上下文&#xff08;Security Context&#xff09; 文件安全上下文查看 …...

Acwing算法心得——街灯(差分)

大家好&#xff0c;我是晴天学长&#xff0c;差分广泛用于一段范围的加减运算&#xff0c;可以优化时间复杂度&#xff0c;需要的小伙伴请自取哦&#xff01;如果觉得写的不错的话&#xff0c;可以点个关注哦&#xff0c;后续会继续更新的。&#x1f4aa;&#x1f4aa;&#x1…...

streamlit执行报错WARNING,重新安装碰到问题如何解决

streamlit执行报错WARNING&#xff0c;重新安装碰到问题如何解决 如何解决1、卸载已经安装的程序2、再次安装程序3、出现如下yinstaller 警告问题&#xff1a;4、又出现“which is not on PATH”警告。5、解决方案 发现在安装的时候有很多WARNING出现&#xff0c;但是没有但回事…...

《C++设计模式》——行为型

前言 行为型模式是对在不同的对象之间划分责任和算法的抽象化。行为型模式不仅仅关注类和对象的结构&#xff0c;而且重点关注它们之间的相互作用。 Interpreter(解释器) Template Method(模板方法) GOOD&#xff1a;把不变的代码部分都转移到父类中&#xff0c;将可变的代…...

什么是原生IP?原生IP与住宅IP有何区别?

相信许多做跨境的都会接触到IP代理&#xff0c;比如电商平台、社媒平台、收款平台等等&#xff0c;都会检测IP。那也会经常听到一些词汇&#xff1a;原生IP、住宅IP&#xff0c;这两者之间有什么区别呢&#xff1f;什么业务需要用到呢&#xff1f;接下来带大家具体了解一下。 什…...

element-plus 表格-自定义样式实现

效果如下 代码如下 <template><h2>表格自定义样式</h2><div style"background-color: cadetblue; height: 600px;"><div class"regulaContainer"><el-table ref"tableRef" :data"tableData" border …...

MVCC

MVCC&#xff08;Multi-Version Concurrency Control&#xff09;是数据库管理系统&#xff08;DBMS&#xff09;中的一种技术&#xff0c;用于管理并发访问数据&#xff0c;允许多个事务同时进行而不互相干扰&#xff0c;同时保持数据的一致性。 MVCC 的工作原理如下&#xf…...

你不知道的JavaScript---对象

1.语法 对象可以通过两种方式定义&#xff1a;一种是对象字面量形式&#xff0c;一种是构造形式 对象字面量&#xff1a; var muObject {key: value }构造形式的&#xff1a; var myObject new Object() myObject.key value不管是使用对象字面量形式还是构造形式创建出来…...

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…...

Android Wi-Fi 连接失败日志分析

1. Android wifi 关键日志总结 (1) Wi-Fi 断开 (CTRL-EVENT-DISCONNECTED reason3) 日志相关部分&#xff1a; 06-05 10:48:40.987 943 943 I wpa_supplicant: wlan0: CTRL-EVENT-DISCONNECTED bssid44:9b:c1:57:a8:90 reason3 locally_generated1解析&#xff1a; CTR…...

超短脉冲激光自聚焦效应

前言与目录 强激光引起自聚焦效应机理 超短脉冲激光在脆性材料内部加工时引起的自聚焦效应&#xff0c;这是一种非线性光学现象&#xff0c;主要涉及光学克尔效应和材料的非线性光学特性。 自聚焦效应可以产生局部的强光场&#xff0c;对材料产生非线性响应&#xff0c;可能…...

python打卡day49

知识点回顾&#xff1a; 通道注意力模块复习空间注意力模块CBAM的定义 作业&#xff1a;尝试对今天的模型检查参数数目&#xff0c;并用tensorboard查看训练过程 import torch import torch.nn as nn# 定义通道注意力 class ChannelAttention(nn.Module):def __init__(self,…...

【WiFi帧结构】

文章目录 帧结构MAC头部管理帧 帧结构 Wi-Fi的帧分为三部分组成&#xff1a;MAC头部frame bodyFCS&#xff0c;其中MAC是固定格式的&#xff0c;frame body是可变长度。 MAC头部有frame control&#xff0c;duration&#xff0c;address1&#xff0c;address2&#xff0c;addre…...

2025年能源电力系统与流体力学国际会议 (EPSFD 2025)

2025年能源电力系统与流体力学国际会议&#xff08;EPSFD 2025&#xff09;将于本年度在美丽的杭州盛大召开。作为全球能源、电力系统以及流体力学领域的顶级盛会&#xff0c;EPSFD 2025旨在为来自世界各地的科学家、工程师和研究人员提供一个展示最新研究成果、分享实践经验及…...

java 实现excel文件转pdf | 无水印 | 无限制

文章目录 目录 文章目录 前言 1.项目远程仓库配置 2.pom文件引入相关依赖 3.代码破解 二、Excel转PDF 1.代码实现 2.Aspose.License.xml 授权文件 总结 前言 java处理excel转pdf一直没找到什么好用的免费jar包工具,自己手写的难度,恐怕高级程序员花费一年的事件,也…...

Qt Widget类解析与代码注释

#include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this); }Widget::~Widget() {delete ui; }//解释这串代码&#xff0c;写上注释 当然可以&#xff01;这段代码是 Qt …...

【磁盘】每天掌握一个Linux命令 - iostat

目录 【磁盘】每天掌握一个Linux命令 - iostat工具概述安装方式核心功能基础用法进阶操作实战案例面试题场景生产场景 注意事项 【磁盘】每天掌握一个Linux命令 - iostat 工具概述 iostat&#xff08;I/O Statistics&#xff09;是Linux系统下用于监视系统输入输出设备和CPU使…...

Rust 异步编程

Rust 异步编程 引言 Rust 是一种系统编程语言,以其高性能、安全性以及零成本抽象而著称。在多核处理器成为主流的今天,异步编程成为了一种提高应用性能、优化资源利用的有效手段。本文将深入探讨 Rust 异步编程的核心概念、常用库以及最佳实践。 异步编程基础 什么是异步…...