模板解析期间发生错误(模板:“类路径资源[templates / user-form / user-signup.html]”)

时间:2020-11-02 19:08:48

标签: java html css spring spring-boot

我遇到此错误,而不是如何解决

@Controller
public class UserController {
    
        @Autowired
        UserService userService;
        @Autowired
        RoleRepository roleRepository;
        
        
        @GetMapping({"/","/login"})
        public String index() {
            return "index";

        }
        
        
        @GetMapping("/signup")
        public String signup(Model modelo) {
            Role userRole=roleRepository.findByName("USER");
            List<Role>roles=Arrays.asList(userRole);
            modelo.addAttribute("userForm", new User());
            modelo.addAttribute("roles",roles);
            modelo.addAttribute("signup",true);

            return "user-form/user-signup";
        }
        
        @PostMapping("/signup")
        public String postSignup(@Valid @ModelAttribute("userForm")User user,BindingResult result,Model modelo){   
            if(result.hasErrors()) {

                return signup(modelo);
                
                }else {
                    try {
                        userService.createUser(user);
                    } catch (Exception e) {
                        modelo.addAttribute("formErrorMessage",e.getMessage());
                        return signup(modelo);

                        
                    }
                    
                    
                }
            return "index";
            
        }
        
        
        
        
        
        @GetMapping("/userForm")
        public String userForm(Model modelo) {
            modelo.addAttribute("userForm", new User());
            modelo.addAttribute("userList",userService.getAllUsers());
            modelo.addAttribute("roles",roleRepository.findAll());
            modelo.addAttribute("listTab","active");
            return "user-form/user-view";
            
            
        }
        
        
        @PostMapping("/userForm")
        
        public String createUser(@Valid @ModelAttribute("userForm")User user,BindingResult result,ModelMap modelo){   
        
            if(result.hasErrors()) {
                modelo.addAttribute("userForm", user);
                modelo.addAttribute("formTab","active");
                }else {
                    try {
                        userService.createUser(user);
                        modelo.addAttribute("userForm", new User());
                        modelo.addAttribute("listTab","active");
                    } catch (Exception e) {
                        modelo.addAttribute("formErrorMessage",e.getMessage());
                        modelo.addAttribute("userForm", user);
                        modelo.addAttribute("formTab","active");
                        modelo.addAttribute("userList",userService.getAllUsers());
                        modelo.addAttribute("roles",roleRepository.findAll());
                        
                    }
                    
                    
                }
            
            
            
            modelo.addAttribute("userList", userService.getAllUsers());
            modelo.addAttribute("roles",roleRepository.findAll());
            return "user-form/user-view";
    }
        
        @GetMapping("/editUser/{id}")
        public String getEditUserForm(Model model, @PathVariable(name="id") Long id) throws Exception {
        
            User usertToEdit=userService.getUserById(id);
            
            model.addAttribute("userForm", usertToEdit);
            model.addAttribute("userList",userService.getAllUsers());
            model.addAttribute("roles",roleRepository.findAll());
            model.addAttribute("formTab","active");
            model.addAttribute("editMode","true");
            model.addAttribute("passwordForm",new ChangePasswordForm(id));

             return "user-form/user-view";
            
        }
        
        @PostMapping("/editUser")
        
        public String postEditUserForm(@Valid @ModelAttribute("userForm")User user,BindingResult result,ModelMap modelo){ 
            if(result.hasErrors()) {
                modelo.addAttribute("userForm", user);
                modelo.addAttribute("formTab","active");
                modelo.addAttribute("editMode","true");
                modelo.addAttribute("passwordForm",new ChangePasswordForm(user.getId()));
                }else {
                    try {
                        userService.updateUser(user);
                        modelo.addAttribute("userForm", new User());
                        modelo.addAttribute("listTab","active");
                        modelo.addAttribute("editMode","false");

                    } catch (Exception e) {
                        modelo.addAttribute("formErrorMessage",e.getMessage());
                        modelo.addAttribute("userForm", user);
                        modelo.addAttribute("formTab","active");
                        modelo.addAttribute("userList",userService.getAllUsers());
                        modelo.addAttribute("roles",roleRepository.findAll());
                        modelo.addAttribute("editMode","false");
                        modelo.addAttribute("passwordForm",new ChangePasswordForm(user.getId()));

                    }
                    
                    
                }
            
            
            
            modelo.addAttribute("userList", userService.getAllUsers());
            modelo.addAttribute("roles",roleRepository.findAll());
            return "user-form/user-view";
        
        }
        
        @GetMapping("/userForm/cancel")
        public String cancelEditUser(ModelMap model) {
            return "redirect:/userForm";
        }
        
    
        @GetMapping("/deleteUser/{id}")
        public String deleteUser(Model model, @PathVariable(name="id") Long id) {
            
            try {
                userService.deleteUser(id);
                
            } catch (UsernameOrIdNotFound el) {
                
                model.addAttribute("listErrorMessage",el.getMessage());
                
            }
            
            return userForm(model);
            
        }
        
        @PostMapping("/editUser/changePassword")
        public ResponseEntity postEditUseChangePassword(@Valid @RequestBody ChangePasswordForm form, Errors errors) {

        try {
            
            if (errors.hasErrors()) {
                 String result = errors.getAllErrors()
                 .stream().map(x -> x.getDefaultMessage())
                 .collect(Collectors.joining(""));
                 
                    throw new Exception(result);

            }

            userService.changePassword(form);
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
            
            
            return ResponseEntity.ok("Success");
            //
            
        }   
}
<div th:with="disableFields=!${editMode} and ${#authorization.expression('hasRole(''ROLE_USER'')')}">

<form class"form" role="form" autocomplete="off" th:object="${userForm}"  th:action="${signup} ?/@{/signup} : (${editMode} ?@{/editUser} :@{/userForm})" method="post"   >

<!--Es necesario para poder pasar la validacion del Model-->
    <input class="form-control" type=hidden th:field="${userForm.id}" th:if="${editMode}">
<!--Es necesario para poder pasar la validacion del Model-->

    <input class="form-control" type=hidden name="password" th:field="${userForm.password}" th:if="${editMode}">



<div class="form-group row">
    <label class="col-lg-3 col-form-label form-control-label">Nombre</label>
    <div class="col-lg-9">
        <input class="form-control" type="text" th:field="${userForm.firstName}" th:disabled="${disableFields}">
        <div class="alert-danger" th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">Name Error</div>
    </div>
    </div>
<div class="form-group row">
    <label class="col-lg-3 col-form-label form-control-label">Apellido
        </label>
    <div class="col-lg-9">
        <input class="form-control" type="text"  th:field="${userForm.lastName}" th:disabled="${disableFields}">
        <div class="alert-danger" th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}">Name Error</div>
    </div>
    </div>

<div class="form-group row">
    <label class="col-lg-3 col-form-label form-control-label">Email</label>
    <div class="col-lg-9">
        <input class="form-control" type="email" th:field="${userForm.email}" th:disabled="${disableFields}">
        <div class="alert-danger" th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Name Error</div>
    </div>
    </div>
<div class="form-group row">
    <label class="col-lg-3 col-form-label form-control-label">Usuario</label>
    <div class="col-lg-9">
        <input class="form-control" type="text" th:field="${userForm.username}" th:disabled="${disableFields}" >
        <div class="alert-danger" th:if="${#fields.hasErrors('username')}" th:errors="*{username}">Name Error</div>
    </div>
    </div>

<div class="form-group row">
        <label th:text="Roles" class="col-lg-3 col-form-label form-control-label"></label>
        <div class="col-lg-9">
            <select  class="form-control" th:size="@{signup}?1 :3"  th:field="${userForm.roles}" th:disabled="${disableFields}">
            <option th:each="role :${roles}" th:value="${role.id}" th:text="${role.name}">
                
                </option>
            </select>
                    <div class="alert-danger" th:if="${#fields.hasErrors('roles')}" th:errors="*{roles}">Name Error</div>
    
            
        </div>
    </div>


<div class="form-group row" th:if="${editMode==null or editMode==false}">
    <label class="col-lg-3 col-form-label form-control-label">Password</label>
    <div class="col-lg-9">
        <input class="form-control" type="password"  th:field="${userForm.password}" th:disabled="${disableFields}">
        <div class="alert-danger" th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Name Error</div>
    </div>
    </div>
<div class="form-group row"  th:if="${editMode==null or editMode==false}">
    <label class="col-lg-3 col-form-label form-control-label">Confirm</label>
    <div class="col-lg-9">
        <input class="form-control" type="password"  th:field="${userForm.confirmPassword}" th:disabled="${disableFields}">
        <div class="alert-danger" th:if="${#fields.hasErrors('confirmPassword')}" th:errors="*{confirmPassword}">Name Error</div>
    </div>
    </div>
<div class="form-group row">
    <div class="col-lg-12 text-center">
        <a class="btn btn-secondary" th:href="@{'/userForm/cancel'}"> Cancel</a>
        <button type="button" class="btn btn-secondary" data-toggle="modal" th:if="${editMode}" data-backdrop="false"  data-dismiss="modal" data-target="#changePasswordModal">Change Password</button>     
        <div th:if="${editMode}" th:include="user-form/change-password.html" th:remove="tag"></div>
        <input type="submit" class="btn btn-primary" 
        value="Save Changes" th:value="${editMode}?'Save User':'Create User'">
    </div>  
</div>
    <div class="alert alert-danger text-center" th:if="${formErrorMessage}" th:text="${formErrorMessage}">Error MEssage</div>
    <div class="alert alert-success text-center d-none" id="formSuccess" th:if="${editMode}" >Success Message</div>

</form>
</div>

错误:

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "${/signup} ?/@{/signup} : (${editMode} ?@{/editUser} :@{/userForm})" (template: "user-form/user-form.html" - line 3, col 75)
    at org.thymeleaf.standard.expression.StandardExpressionParser.parseExpression(StandardExpressionParser.java:131) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.standard.expression.StandardExpressionParser.parseExpression(StandardExpressionParser.java:62) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.standard.expression.StandardExpressionParser.parseExpression(StandardExpressionParser.java:44) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.engine.EngineEventUtils.parseAttributeExpression(EngineEventUtils.java:220) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.engine.EngineEventUtils.computeAttributeExpression(EngineEventUtils.java:207) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.standard.processor.AbstractStandardExpressionAttributeTagProcessor.doProcess(AbstractStandardExpressionAttributeTagProcessor.java:125) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.engine.Model.process(Model.java:282) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1587) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleOpenElementEnd(TemplateHandlerAdapterMarkupHandler.java:304) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleOpenElementEnd(InlinedOutputExpressionMarkupHandler.java:278) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
    at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleOpenElementEnd(OutputExpressionInlinePreProcessorHandler.java

1 个答案:

答案 0 :(得分:0)

  1. 在方法“ public String signup(Model modelo){”中,缺少属性“ editMode”。请修复
modelo.addAttribute("editMode",true);  //maybe like it 
  1. 在html的第3行中,您应按以下方式更改th:action
<form class"form" role="form" autocomplete="off" th:object="${userForm}"  th:action="${signup} ? '/signup' : (${editMode} ? '/editUser' : '/userForm')" method="post"   >