【SpringBoot04】学习笔记--web开发

1、SpringMVC自动配置概览

  • 大多场景我们都无需自定义配置
    • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
    • 内容协商视图解析器和BeanName视图解析器
    • Support for serving static resources, including support for WebJars (covered later in this document)).
    • 静态资源(包括webjars)
    • Automatic registration of Converter, GenericConverter, and Formatter beans.
    • 自动注册 Converter,GenericConverter,Formatter
    • Support for HttpMessageConverters (covered later in this document).
    • 支持 HttpMessageConverters (后来我们配合内容协商理解原理)
    • Automatic registration of MessageCodesResolver (covered later in this document).
    • 自动注册 MessageCodesResolver (国际化用)
    • Static index.html support.
    • 静态index.html 页支持
    • Custom Favicon support (covered later in this document).
    • 自定义 Favicon
    • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
    • 自动使用 ConfigurableWebBindingInitializer ,(DataBinder负责将请求数据绑定到JavaBean上)
    If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
    不用@EnableWebMvc注解。使用 @Configuration + WebMvcConfigurer 自定义规则
    If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.
    声明 WebMvcRegistrations 改变默认底层组件
    If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.
    使用 @EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration 全面接管SpringMVC

区分
static-locations: [classpath:/haha/]

static-path-pattern: /res/**

2、静态资源访问

只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources

  • 访问 : 当前项目根路径/ + 静态资源名

  • 原理: 静态映射/**。

    请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面
    改变默认的静态资源路径

spring:
  mvc:
    static-path-pattern: /res/**
  resources:
    static-locations: [classpath:/haha/]

2.1、静态资源访问前缀

默认无前缀

spring:
  mvc:
    static-path-pattern: /res/**

当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找

3、webjar

自动映射 /webjars/**
https://www.webjars.org/

  <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>3.5.1</version>
    </dependency>

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径

2.2欢迎页支持

  • 静态资源路径下 index.html

  • 可以配置静态资源路径

  • 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问

spring:
  mvc:
       static-path-pattern: /res/** 

这个会导致welcome page功能失效
resources:
static-locations: [classpath:/haha/]
• controller能处理/index

2.3、自定义 Favicon

favicon.ico 放在静态资源目录下即可。
spring:

mvc:

static-path-pattern: /res/** 这个会导致 Favicon 功能失效

基本注解

@PathVariable、@RequestHeader、@ModelAttribute、@RequestParam、@MatrixVariable、@CookieValue、@RequestBody

  • @PathVariable路径变量,获取路径变量的值,也可以用map把所有的路径变量提取出来

  • @RequestHeader(“User-Agent”) String userAgent 获取一个请求头
    @RequestHeader Map<String,String> header获取所有请求头,并放到map中,map类型必须为string,string类型

  • @RequestParam(“age”) Integer age,
    @RequestParam(“inters”) List inters,获取指定请求参数
    @RequestParam Map<String,String> params获取所有参数放到map中

  • @CookieValue("_ga") String _ga,获取-ga的cookie值
    @CookieValue("_ga") Cookie cookie 获取-ga的cookie

  • @RequestBody只有 post请求才有请求体,表单提交时用到

 @PostMapping("/save")
    public Map postMethod(@RequestBody String content){
        Map<String,Object> map = new HashMap<>();
        map.put("content", content);
        return map;
    }
  • @RequestAttribute(获取request域属性)
@Controller
public class RequestController {
    @RequestMapping("/goto")
    public String goToPage(HttpServletRequest request){
        request.setAttribute("msg", "成功可乐");
        request.setAttribute("code", 200);

        return "forward:/success";//转发到/success请求
    }
    @ResponseBody
    @GetMapping("/success")
    public Map success(@RequestAttribute("msg") String msg,
                          @RequestAttribute("code") Integer code,
                          HttpServletRequest request){

        Object msg1 = request.getAttribute("msg");
        Map<String,Object> map = new HashMap<>();
        map.put("requestMethod", msg1);
        map.put("annotationMsg", msg);


        return map;
    }

}
  • @MatrixVariable(矩阵变量)
    1、语法: 请求路径:/cars/sell;low=34;brand=byd,audi,yd
    2、SpringBoot默认是禁用了矩阵变量的功能
    手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
    removeSemicolonContent(移除分号内容)支持矩阵变量的
    3、矩阵变量必须有url路径变量才能被解析
   @GetMapping("/cars/sell")
    public Map carSell(@MatrixVariable("low") Integer low,
                       @MatrixVariable("brand") List<String> brand){
        Map<String,Object> map = new HashMap<>();
        map.put("low", low);
        map.put("brand", brand);


        return map;

    }

开启矩阵变量
方法一:

@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {
   @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        //不移除分号后边的内容
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
    }

方法二:

@Configuration(proxyBeanMethods = false)
public class WebConfig /*implements WebMvcConfigurer*/ {
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
        methodFilter.setMethodParam("_m");
        return methodFilter;
    }

    //1、WebMvcConfigurer定制化SpringMVC的功能
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){

        WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }
        };
        return webMvcConfigurer;

    }


}

复杂参数:Map、Model(map、model里面的数据会被放在request的请求域 request.setAttribute)、Errors/BindingResult、RedirectAttributes( 重定向携带数据)、ServletResponse(response)、SessionStatus、UriComponentsBuilder、ServletUriComponentsBuilder

 @GetMapping("/params")
    public String testParam(Map<String,Object> map,
                            Model model,
                            HttpServletRequest request,
                            HttpServletResponse response){
        map.put("hello", "world666");
        model.addAttribute("world", "hello666");
        request.setAttribute("message", "helloworld");
        Cookie cookie = new Cookie("c1","v1");
        cookie.setDomain("localhost");
        response.addCookie(cookie);
        return "forward:/success";


    }
@ResponseBody
    @GetMapping("/success")
    public Map success(@RequestAttribute(value = "msg",required = false) String msg,
                          @RequestAttribute(value = "code",required = false) Integer code,
                          HttpServletRequest request){

//        Object msg1 = request.getAttribute("msg");
        Map<String,Object> map = new HashMap<>();
//        map.put("requestMethod", msg1);
//        map.put("annotationMsg", msg);
        Object hello = request.getAttribute("hello");
        Object world = request.getAttribute("world");
        Object message = request.getAttribute("message");
        map.put("hello", hello);
        map.put("world", world);
        map.put("message", message);



        return map;
    }

自定义对象参数:
可以自动类型转换与格式化,可以级联封装。

/**
 *     姓名: <input name="userName"/> <br/>
 *     年龄: <input name="age"/> <br/>
 *     生日: <input name="birth"/> <br/>
 *     宠物姓名:<input name="pet.name"/><br/>
 *     宠物年龄:<input name="pet.age"/>
 */
@Data
public class Person {
    
    private String userName;
    private Integer age;
    private Date birth;
    private Pet pet;
    
}

@Data
public class Pet {

    private String name;
    private String age;

}

数据响应和内容协商

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值