159_SpringBoot_web 普通参数与基本注解

举报
alexsully 发表于 2021/09/23 19:02:15 2021/09/23
1.7k+ 0 0
【摘要】 参数&注解

1 注解: 
@PathVariable,@RequestHeader,

html

      <ul>
            <a href="car/1/owner/alex">car/{id}/owner/{username}</a> <br>
            <a href="dog/2/owner/bob?age=18&inters=basketball&inters=game">dog/{id}/owner/{username}</a>
        </ul>

controller

@RestController
public class ParameterTestController {
    @GetMapping("/car/{id}/owner/{username}")
    public Map<String, Object> getCar(@PathVariable("id") Integer id,
                                      @PathVariable("username") String name,
                                      @PathVariable Map<String,String> pv,
                                      @RequestHeader("Host") String host,
                                      @RequestHeader(value = "Host") String host2,
                                      @RequestHeader Map<String, Object> headers  ){
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",id);
        map.put("name",name);
        map.put("pv",pv);
        map.put("Host", host);
        map.put("Host2", host2);
        map.put("headers" , headers);
        return map;
    }}


@RequestParam,@CookieValue,

 @GetMapping("/dog/{id}/owner/{username}")
    public Map<String, Object> getDog(@RequestParam("age") Integer in1,
                                      @RequestParam("inters")List<String> list,
                                      @RequestParam Map<String, Object> map_all,
                                      @CookieValue(name = "Idea-157d2a49") String cookie,
                                      @CookieValue(value ="JSESSIONID" ) Cookie cookie2){

        HashMap<String, Object> map = new HashMap<>();
        map.put("age", in1);
        map.put("inters", list);
        map.put("Idea-157d2a49", cookie);
        map.put("cookies", cookie2);
        map.put("map_all", map_all);
        System.out.println(cookie2.getName()+"===>"+cookie2.getValue()); // 是个cookie对象
        return map;
    }

@RequestBody,

   @PostMapping("/save")
    public Map saveuser(@RequestBody String content){
        HashMap<String, Object> map = new HashMap<>();
        map.put("RequestBody",content);
        return map;
    }

@RequestAttribute, @ModelAttribute,

@Controller
public class RequestAttributeController {

    @GetMapping("/goto")
    public String goToPage(HttpServletRequest request){

        request.setAttribute("msg","成功了...");
        request.setAttribute("code",200);
        return "forward:/success";  //转发到  /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("reqMethod_msg",msg1);   //  request方式获取
        map.put("annotation_msg",msg);  //   通过参数获取
        return map;  //{"reqMethod_msg":"成功了...","annotation_msg":"成功了..."}
    }
}

@MatrixVariable SpringBoot默认是禁用了矩阵变量的功能

/boss/1;age=20/2;age=20   分号前面是路径,分号后面是矩阵变量(key=value) 多个变量用;分割

<a href="/cars/sell;low=34;brand=byd,audi,yd">@MatrixVariable(矩阵变量)</a>
public class WebConfig  implements WebMvcConfigurer {
     @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                // 不移除;后面的内容。矩阵变量功能就可以生效
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }}
  //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 Servlet API:
WebRequest、ServletRequest、MultipartRequest、 HttpSession、javax.servlet.http.PushBuilder、Principal、InputStream、Reader、HttpMethod、Locale、TimeZone、ZoneId

3 复杂参数:
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");
        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<>();
        Object hello = request.getAttribute("hello");
        Object world = request.getAttribute("world");
        Object message = request.getAttribute("message");

        map.put("reqMethod_msg",msg1);
        map.put("annotation_msg",msg);
        map.put("hello",hello);
        map.put("world",world);
        map.put("message",message);

        return map;

    }

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

       <form action="/saveuser" method="post">
            姓名: <input name="userName" value="zhangsan"/> <br/>
            年龄: <input name="age" value="18"/> <br/>
            生日: <input name="birth" value="2019/12/10"/> <br/>
            <!--    宠物姓名:<input name="pet.name" value="阿猫"/><br/>-->
            <!--    宠物年龄:<input name="pet.age" value="5"/>-->
            宠物: <input name="pet" value="啊猫,3"/>
            <input type="submit" value="保存"/>
        </form>

/**
     * 数据绑定:页面提交的请求数据(GET、POST)都可以和对象属性进行绑定
     * @param person
     * @return
     */
  @PostMapping("/saveuser")
    public Person saveuser(Person person){
        return person;
    }

自定义转换器

//1、WebMvcConfigurer定制化SpringMVC的功能
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                // 不移除;后面的内容。矩阵变量功能就可以生效
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }

            @Override
            public void addFormatters(FormatterRegistry registry) {
                registry.addConverter(new Converter<String, Pet>() {
                    @Override
                    public Pet convert(String source) {
                        // 啊猫,3
                        if(!StringUtils.isEmpty(source)){
                            Pet pet = new Pet();
                            String[] split = source.split(",");
                            pet.setName(split[0]);
                            pet.setAge(Integer.parseInt(split[1]));
                            return pet;
                        }
                        return null;
                    }
                });

            }
        };
    }

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。