springboot学习笔记

springboot学习笔记,第1张

springboot学习笔记

此文章是看b站springboot教学视频写的一些小笔记

静态资源导入

resources文件夹下有resources、static、public文件夹,优先级依次递减。
建立的js文件通过localhost:8080/test.js访问。

  • public里放公共的资源
  • static放静态的资源,如图片(默认使用static处理静态资源)
  • resources放上传的文件
首页

在resources文件夹下新建一个index.html即为首页,localhost:8080/即可访问。
跳转的写法:

//如果是放在templates目录下的页面,只能通过controller来跳转
@Controller
public class IndexController {

    @RequestMapping("/index")
    public String index(){
        return "index";  //作用是 链接到了index.html
    }
}
Thymeleaf模板引擎

之前使用的是jsp,现在大多使用Thymeleaf。
如果需要使用Thymeleaf,只需导入对应的依赖。将HTML页面放在templates目录下。
使用:
放入约束/头文件

  • 链接→th:href
  • 文本→th:text
  • 表达式→${…}
  • 选择表达式→*{…}
  • 消息→#{…}
  • URL→@{…}
    例子:
    java文件中写:
@RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg","hellospringboot");
        return "test";
    }

HTML文件中写:


Thymeleaf语法

完整用法看官方文档

@RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg","hellospringboot");
        return "test";
    }
   

 
[[${user}]]
MVC配置原理

在讲源码,听不懂

package com.example.test.config;

import org.apache.tomcat.jni.Local;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

//如果想diy一些定制化的功能,只要写这个组件,然后把它交给springboot,springboot就会帮我们自动装配!
//扩展 springmvw    siapatchservlet
@Configuration
public class MyMvcConfig  implements WebMvcConfigurer {
    //ViewResolver 实现了视图解析器接口的类,我们就可以把它看做视图解析器
    @Bean
    public ViewResolver myViewResolver(){
        return new MyViewResolver();
    }
    
    //自定义了一个自己的视图解析器MyViewResolver
    public static class MyViewResolver implements ViewResolver{
        @Override
        public View resolveViewName(String viewName, Locale locale) throws Exception{
            return null;
        }
    }
    
}
扩展SpringMVC

在讲源码,听不懂

package com.example.test.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration 
@EnableWebMvc  //导入了一个类:DelegatingWebMvcConfiguration:从容器中获取所有的webmvcconfig
public class MyMvcConfig  implements WebMvcConfigurer {
    //视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/index").setViewName("test");
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5692001.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存