在控制器中发布和获取映射

时间:2018-12-19 19:51:15

标签: java spring-boot mapping

很难用英语解释我的问题,因为我不是母语人士。但我希望,你会理解我的。我是春季新人。我有两个POJO类PC和PcCharacteristics。因此,我有控制器。当我在台式PC中单击链接“特性”时,我肯定会直接指向charactTable。在我的PcCharController中,这个方向映射就像@GetMapping("pc/{id}/characts")。我应该在PcCharController的saveCharact方法中的“返回”中写些什么,以将我重定向到按PC ID显示字符的CharactTable?这是我的控制器,底部是saveChar。我的deleteChar方法也有同样的问题。

@Controller
public class PcCharsController {

final private PcRepository pcRepository;
final private PcCharactRepository pcCharactRepository;

public PcCharsController(PcRepository pcRepository, PcCharactRepository pcCharactRepository) {
    this.pcRepository = pcRepository;
    this.pcCharactRepository = pcCharactRepository;
}

@GetMapping("pc/{id}/characts")
public String pcCharList(@PathVariable Long id, Model model) throws Exception{

    Pc pc = pcRepository.findById(id).orElseThrow(() -> new Exception("PostId " + id + " not found"));
    List<PcCharacts> pcChars = pc.getCharacts();
    model.addAttribute("model", pc.getModel());
    model.addAttribute("pcChars", pcChars);
    return "charList";
}

@PostMapping("pc/{id}/characts")
public String addChar(@RequestParam Long id,
                      @RequestParam String name,
                      @RequestParam String value,
                      Model model) throws Exception {
    Pc pc = pcRepository.findById(id).orElseThrow(() -> new Exception("PostId " + id + " not found"));
    PcCharacts pcCharacts = new PcCharacts(name, value, pc);
    pcCharactRepository.save(pcCharacts);
    List<PcCharacts> pcChars = pc.getCharacts();
    model.addAttribute("pcChars", pcChars);
    return "redirect:";
}

@GetMapping("/charact/{pcChars}")
public String editCharact(@PathVariable PcCharacts pcChars, Model model){
    model.addAttribute("pcChars", pcChars);
    return "editPcChar";
}

//HERE IS A PROBLEM
@PostMapping("pc/characts/save") //OR HERE
public String charSave(@RequestParam String name,
                       @RequestParam String value,
                       @RequestParam("id") PcCharacts pcChars){
    pcChars.setName(name);
    pcChars.setValue(value);
    pcCharactRepository.save(pcChars);
    return "redirect:/pc/{id}/characts"; //HERE
}

@GetMapping("/charact/delete/{id}")
public String deletePc(@PathVariable("id") PcCharacts pcChars){
    pcCharactRepository.delete(pcChars);
    return "redirect:/pc/{id}/";
}

}

0 个答案:

没有答案