从Path捕获元素

时间:2019-06-06 21:09:54

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

你好,我正在处理重定向到其他页面的值,我在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/";
            }

1 个答案:

答案 0 :(得分:0)

要获取请求参数,您需要在注释中或以变量名形式传递参数的实际名称。您还必须从映射路径中删除{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<String, String> params

有关更多信息,请阅读{{3}}。