SpringBoot注解以及Web应用开发

SpringBoot的注解

  • @SpringBootApplication :与@ComponentScan、@Configuration、@EnableAutoConfiguration三个注解等价
  • @ComponentScan :用于扫描组件,可以自动发现和装配Bean且在发现和装配Bean时把Bean加入程序的上下文
  • @Configuration :标注于类上,等同于Spring的XML文件的一个
  • @EnableAutoConfiguration : 启动自动装配
  • @RestController :是@Controller(注解一个控制器)和@ResponseBody(改变Springmvc路由)的合集
  • @Bean: 标注在方法上,等同于Spring的XML文件中配置的Bean
  • @Value :用来注入SpringBoot配置文件application.properties中配置的属性值
  • @ControllerAdvice: 包含了@Component,可以被扫描到,统一处理异常
  • @Resource: 可以用在字段、构造方法、方法,并进行自动注入。 和@Autowire不同的是 @Autowired按类型自动注入,@Resource按名称进行注入
  • @Service :标注在类上 表示被标注的类是一个Component 位于服务层
  • @Repository :标注在类 表示被标注的类是一个Component 位于数据存储层
  • @Component: 标注在类上 是一种泛指 表示被标注的对象是组件

SpringBoot的Web应用开发

SpringBoot中的静态页面

在SpringBoot中,默认把静态资源(html文件,图片、css、js)放在src/main/resources/static下;可以看作是默认首页
SpringBoot注解以及Web应用开发_第1张图片

实现基于Thymeleaf的Web应用

Thymeleaf是springBoot推荐的动态Web页面的模板引擎

添加Thymeleaf依赖

也可以在创建时勾选Thymeleaf;也可以在pom.xml文件中导入依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
     <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

在src/main/resources/templates下创建Web页面(.html),在页面中添加thymeleaf的命名空间

在这里插入图片描述

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    <title>主页title>
head>
<body>
<h1>
    这是一个页面
h1>
<p th:text="'hello,'+${ userName }">p>


body>
html>

创建Controller

使用@Controller标注控制器;
@RequestParam参数:
name :参数名
required :是否必要
defaultValue :默认值

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
 * @author Una
 * @date 2022/8/20 17:39
 * @description:
 */

@Controller
public class HelloController {
    @GetMapping(value = "/hello")
    public String getHello(@RequestParam(name = "userName",required = false,defaultValue = "World") String UserName, Model model){
        model.addAttribute("userName" ,UserName);
        return "hello";
    }
}

运行效果

SpringBoot注解以及Web应用开发_第2张图片
SpringBoot注解以及Web应用开发_第3张图片

实现基于RESTful风格的Web应用

什么是RESTful风格

  1. REST(Representational State Transfer):描述了一个架构样式的网络系统,是一组架构约束条件和使用原则,凡是满足了这些约束条件和使用原则的应用程序或设计就是RESTful
  2. REST原则:
  • a、客户端和服务器之间的交互是无状态的;即使用http协议进行交互
  • b、客户端的无状态请求可以由任意可用的服务器来应答
  • c、服务器端的应用程序状态和功能可以分为各种资源,每个资源都使用URI得到一个唯一的地址
  • d、客户端和服务器端在进行交互时使用的传输方法是标准的http方法(get、post、put、delete等)

你可能感兴趣的:(springBoot,spring,JavaWeb,spring,boot,前端,java)