zl程序教程

您现在的位置是:首页 >  其他

当前栏目

SpringBoot2----Web模块的基本注解

2023-03-14 22:33:16 时间

Web模块的基本注解

1.1、注解:

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


@ResponseBody

@ResponseBody,一般是使用在单独的方法上的,需要哪个方法返回json数据格式,就在哪个方法上使用,具有针对性。


@RestController

@RestController,一般是使用在类上的,它表示的意思其实就是结合了@Controller和@ResponseBody两个注解 如果哪个类下的所有方法需要返回json数据格式的,就在哪个类上使用该注解,具有统一性;需要注意的是,使用了@RestController注解之后,其本质相当于在该类的所有方法上都统一使用了@ResponseBody注解,所以该类下的所有方法都会返回json数据格式,输出在页面上,而不会再返回视图。


@PathVariable

@PathVariable(“key”): 传入了对应的key,只拿一个,不传,默认拿所有

@RestController
public class myController
{
    @RequestMapping("/hello/{id}/name/{name}")//占位符
    //获取路径上的占位符
    public Map<String,Object>  hello(@PathVariable("id")Integer id
                                     //这里如果放置一个map,spring会将所用的路径参数放入map中
    ,@PathVariable("name")String name,@PathVariable Map<String,String> map)
    {
           Map<String,Object> m=new HashMap<>();
             m.put("id",id);
             m.put("name",name);
             m.put("map",map);
           return m;
    }
}

这里Map的类型必须是Map<String,String>


@RequestHeader

@RestController
public class myController
{
    @RequestMapping("/hello") 
    public Map<String,Object>  hello(
            //带key,拿一个,否则拿所有
            @RequestHeader("user-agent") String header,
            @RequestHeader Map<String,String> map
            )
    {
           Map<String,Object> m=new HashMap<>();
            m.put("header",header);
            m.put("map",map);
           return m;
    }
}

@RequestParam

@RestController
public class myController
{
    @RequestMapping("/hello")
    public Map<String,Object>  hello(@RequestParam("age")Integer age,
                                     @RequestParam("hobby") List<String> list,
                                     @RequestParam Map<String,String> map)
    {
           Map<String,Object> m=new HashMap<>();
           m.put("age",age);
           m.put("hobby",list);
           m.put("map",map);
           return m;
    }
}

@CookieValue

获取指定cookie的值

@RestController
public class myController
{
    @RequestMapping("/hello")
    public Map<String,Object>  hello(@CookieValue("Idea-60bbb23f")String value)
    {
           Map<String,Object> m=new HashMap<>();
           m.put("value",value);
           return m;
    }
}

如果参数被声明为一个cookie类型,那么就可以获取到该cookie的所有信息:

@RestController
public class myController
{
    @RequestMapping("/hello")
    public Map<String,Object>  hello(@CookieValue("Idea-60bbb23f") Cookie value)
    {
           Map<String,Object> m=new HashMap<>();
           m.put("value",value);
           return m;
    }
}

@RequestBody

获取到请求体中的数据封装到指定的对象中,只有Post方式才有请求体

@RestController
public class myController
{
    @RequestMapping("/hello")
    public Map<String,Object>  hello(@RequestBody String info)
    {
           Map<String,Object> m=new HashMap<>();
           m.put("people",info);
           return m;
    }
}

@RequestAttribute

取出当前请求域中的值

@Controller
public class myController
{
    @RequestMapping("/hello")
    public String hello(HttpServletRequest request)
    {
         request.setAttribute("name","大忽悠");
        request.setAttribute("age","18");
        //这里没有模板引擎的话,无法完成页面跳转
           return "forward:success";//转发到 /success请求
    }

    @ResponseBody
    @RequestMapping("/success")
    public Map<String,Object> show(
            @RequestAttribute("name")String name,
            //这里是转发,因此是一次请求,所以request对象是同一个
            HttpServletRequest request)
    {
        String rn= (String) request.getAttribute("age");
          Map<String,Object> map=new HashMap<>();
          map.put("name",name);
          map.put("age",rn);
          return map;
    }
}

注意: 如果不引入模板引擎,那么就无法完成下面页面渲染,跳转到指定页面等功能


@MatrixVariable—矩阵变量


小应用: cookie禁用后,如何获取Jsessionid ?

session.get(a)<-----服务器按照jsessionid得到session对象<-----cookie中保存了session对象的唯一标识id<-----每次发请求携带该cookie

  • url重写: /abc;jsessionid=xxxx 把cookie中保存的jsessionid的值通过矩阵变量的方式传递,和请求参数区分开来

手动开启矩阵变量的功能


我们可以使用@Configuration + WebMvcConfigurer 自定义配置,覆盖默认配置


对应配置类实现WebMvcConfigurer接口完成对springmvc默认配置的修改

WebMvcConfigurer是一个接口。里面的方法都是default的方法,可以有选择的实现。方法的返回值都是webmvc需要配置的Bean。 所以可以实现这个接口,配合@Configuration注解自定义mvc组件。

@Configuration//表明这是一个配置类
public class WebConfig implements WebMvcConfigurer
{
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper=new UrlPathHelper();
        //不移除分号后面的内容,矩阵变量功能就可以生效
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

直接将对应组件注入容器中

@Configuration//表明这是一个配置类
public class WebConfig
{
    @Bean
    public WebMvcConfigurer webMvcConfigure()
    {
        return new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper=new UrlPathHelper();
                //不移除分号后面的内容,矩阵变量功能就可以生效
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }
        };
    }
}

注意事项1:

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

        map.put("low", low);
        map.put("brand", brand);
        map.put("path", path);
        return map;
    }
}

注意事项2:矩阵变量遇到相同的名字进行获取时,需要通过路径变量来进行区分,即占位符

@RestController
public class myController
{
    // /boss/1;age=20/2;age=10
    @GetMapping("/boss/{bossId}/{empId}")
    //通过路径变量,占位符进行相同名字的区分
    public Map boss(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,
                    @MatrixVariable(value = "age",pathVar = "empId") Integer empAge){
        Map<String,Object> map = new HashMap<>();

        map.put("bossAge",bossAge);
        map.put("empAge",empAge);
        return map;
    }
}