在ModelAndView

时间:2017-12-15 19:28:21

标签: java spring spring-mvc thymeleaf

我有一个读取URL参数的百万美元模板:

http://xxxx:8080/department?action=edit

这样:

<input type="text" th:placeholder="#{department.id}" class="form-control" th:field="*{id}" th:readonly="${param.action[0] == 'edit'}">

基本上,如果action = edit在URL中,则可以编辑。这样可以正常工作,但是当我处理POST方法时,当出现错误时,modelAndView会单独重定向到/ departent而不使用参数:

@RequestMapping(value = "/department", method = RequestMethod.POST)
public ModelAndView department(HttpServletRequest request, @Valid Department department,
                               BindingResult bindingResult) {
    ModelAndView modelAndView = new ModelAndView();
    if (bindingResult.hasErrors()) {
        // data with errores, try again
        modelAndView.setViewName("department");
    } else {
        // all ok. Save and continue
        departmentService.updateDepartment(department);
        modelAndView.setViewName("redirect:departments");
    }
    return modelAndView;
}

当页面重新加载时,我有以下错误消息:

引起:org.thymeleaf.exceptions.TemplateProcessingException:评估SpringEL表达式的异常:&#34; param.action [0] ==&#39; edit&#39;&#34; (模板:&#34;部门&#34; - 第24行,第103栏)

原因是新网址为:

http://xxxx:8080/department

认为我需要使用URL参数是因为链接是由A HREF链接生成的。

我试过了:

modelAndView.getModelMap().put("action", "edit");

但这不起作用。

2 个答案:

答案 0 :(得分:1)

我会通过将param.action[0] == 'edit'变为一个变量并简单地将其添加到模型来简化这一过程。像:

model.addAttribute("isReadOnly", someVariableHereThatMakesItReadOnly);

th:readonly="${isReadOnly}"在您的表单中。

这使您的视图不那么复杂,并允许您在服务器端对isReadOnly的值进行单元测试。然后你可以这样做:

@PostMapping("/department")
public String postDepartment(@Valid Department department,
                             BindingResult result) {
    if (result.hasErrors()) {
        //add error information here
        model.addAttribute("isReadOnly", true); 
        return "department"
    } 
    departmentService.updateDepartment(department);
    return "redirect:/departments";
}

您可能有多种方法可以做到这一点。这只是一种方式。

您也可以在帖子方法中执行return "redirect:/department?action=edit",但之后您需要了解如何显示任何错误消息。

答案 1 :(得分:0)

如果您不想更改代码,请添加到html:

<input type="hidden" name="requestedAction" th:value="${param.action[0]}">

并将RequestMapping方法更改为:

@RequestMapping(value = "/department", method = RequestMethod.POST)
public ModelAndView department(HttpServletRequest request, @Valid Department department, BindingResult bindingResult, @RequestParam String requestedAction) {
    ModelAndView modelAndView = new ModelAndView();
    if (bindingResult.hasErrors()) {
        // data with errores, try again
        modelAndView.setViewName("department?action=" + requestedAction);
    } else {
        // all ok. Save and continue
        departmentService.updateDepartment(department);
        modelAndView.setViewName("redirect:departments");
    }
    return modelAndView;
}