【问题标题】:Catch elements from Path从路径中捕获元素
【发布时间】:2019-06-06 21:09:54
【问题描述】:

您好,我正在处理将值重定向到其他页面我有一个方法发布,其中包含 HashMap 中的选定值,然后使用 redirectAttributes.mergeAttributes 发送它们。它为我创建了带有值的路径,但如何将这些值捕获到 Get 方法控制器

 @GetMapping("/compare/{attrMap}")
    public String compareElements(@RequestParam String attrMap, Model model) {
        System.out.println(attrMap);

        //model.addAttribute("packets", packetService.getAllPackets());
        return "packet/compare";
}    


@PostMapping("/list")
public String postListElements(@ModelAttribute PacketWithChecksCollectionDto packetWithChecksCollectionDto, RedirectAttributes redirectAttributes) {
                List<PacketWithChecksDto> packetWithChecksDtos =
                        packetService
                                .getAllPackets()
                                .stream()
                                .map(p -> PacketWithChecksDto.builder().packetDto(p).build())
                                .collect(Collectors.toList());

                List<PacketWithChecksDto> packet = packetWithChecksCollectionDto.getPacketWithChecksDtos().stream().filter(x -> x.isChecked()).collect(Collectors.toList());
                Map<String, Object[]> attrmap = new HashMap<>();
                attrmap.put("true", packet.stream().map(x -> x.getPacketDto().getId()).toArray());
                attrmap.forEach((k, v) -> System.out.println(k + " " + Arrays.toString(v)));
                redirectAttributes.mergeAttributes(attrmap);
                return "redirect:/packet/compare/";
            }

【问题讨论】:

    标签: java spring redirect model-view-controller path


    【解决方案1】:

    要获取请求参数,您需要在注释中或作为变量名传递参数的实际名称。您还必须从映射路径中删除 {attrMap} 部分,因为它用于路径变量 (@PathVariable) 而不是请求参数:

    @GetMapping("/compare")
    public String compareElements(@RequestParam("abc") String abc, Model model) {
        System.out.println(abc);
        return "packet/compare";
    }
    

    如果你用/compare?abc=xyz调用它,你会得到xyz的结果。

    如果您希望所有参数都为Map,您可以使用@RequestParam Map&lt;String, String&gt; params

    更多信息请阅读docs

    【讨论】:

    • 好的,但是我如何在我的控制器中使用 attrMap。我有一个路径localhost:8086/packet/compare?true=16%2C17,但是如果我想在控制器中显示 attrMap.toString() 什么都不会发生
    • 您正在切换packetcompare。您正在为/compare/{attrMap} 定义映射。所以你要么切换它,要么把你的电话改为/compare/packet
    • 我不明白,我在一个控制器中拥有所有这些方法(“/packet”)。 Post packet/list send selected object to compare in this same controller packet/compare/{attrMap} 我在路径“/packet/compare?true=16%2C17”中有一个对象值 - ID:16 和 ID:17 现在我正在尝试在控制器中对这个 ID 做一些事情,但是当我想要打印或在控制器中做一些事情时我没有它们
    • 你想获取请求参数true=16%2C17吗?如果是,请编辑您的问题以明确说明。
    • @user11042713 我想我误解了你的问题。我更新了我的答案。希望它现在有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    相关资源
    最近更新 更多