@postya

Как исправить ошибку Neither BindingResult nor plain target object for bean name 'patient' available as request attribut в Spring Boot?

Пишу веб приложение на Spring Boot+Thymeleaf+Spring Security+MySQL. После создания post метода в контроллере, перестала открываться страница с полями для ввода.

Есть страница, в которой есть поля для ввода. По клику на кнопку данные из полей должны сохраниться в базе данных.

Сейчас же я не могу даже пройти по http запросу к этим полям и получаю две ошибки:

Neither BindingResult nor plain target object for bean name 'patient' available as request attribute


и
thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/user/profile.html]")


Как можно исправить эти ошибки?

Класс модели:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Patient {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int patientId;

  @NotNull(message = "please enter your name")
  private String name;

  private String email;

  @Temporal(TemporalType.DATE)
  @NotNull(message = "date of birth field should not be empty")
  @Column(name = "date_of_birth")
  private Date dateOfBirth;

  private int phone;

  @NotNull(message = "age should not be empty")
  private int age;

  private String bloodGroup;

  private String gender;

  @NotNull(message = "Please enter your address")
  private String address;

}


Repository:

import com.carevale.carevale.model.Patient;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PatientRepository extends JpaRepository<Patient, Integer> {

}


Service:

import com.carevale.carevale.model.Patient;
import com.carevale.carevale.repository.PatientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PatientService {

  @Autowired
  private PatientRepository patientRepository;

  public void savePatient(Patient patient) {

    patientRepository.save(patient);
  }

}


Controller:

@Controller
public class PatientController {

  @Autowired
  private PatientService patientService;

  @RequestMapping(value = "/user/profile", method= RequestMethod.POST)
  public String savePatient(@Valid @ModelAttribute("patient") Patient patient, Errors errors, Model model) {

    if (errors.hasErrors()) {

      return "user/profile";
    } else {
      model.addAttribute(new Patient());
      return "user/profile";
    }


  }
}


HTML файл с полями:

<form action="#" th:action="@{/user/profile}" th:object="${patient}" method="POST">
                <div class="doctor-fields">

                    <div class="doctor-fields_items_left dates">
                        <!--<h2>Patient ID</h2>
                        <input type="text" placeholder="Patient ID" class="form-control">-->

                        <h2>Name</h2>
                        <input type="text" placeholder="Enter Your Name" class="form-control" th:field="*{name}">
                        <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span>

                        <h2>Date of Birth</h2>
                        <input type="text" autocomplete="off" placeholder="24/05/2012" class="form-control"
                               th:field="*{dateOfBirth}">
                        <span th:if="${#fields.hasErrors('dateOfBirth')}" th:errors="*{dateOfBirth}"></span>

                        <h2>Age</h2>
                        <input type="number" placeholder="Enter Your Age" class="form-control" th:field="*{age}">
                        <span th:if="${#fields.hasErrors('age')}" th:errors="*{age}"></span>

                        <h2>Gender</h2>
                        <select class="form-control form-control-lg" id="gender" name="gender" th:field="*{gender}">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                        <div class="buttons">
                            <button type="reset" class="btn-reset">Reset</button>
                            <button type="submit" class="btn-save">Save</button>
                        </div>

                    </div>
                    <div class="doctor-fields_items_right">
                        <h2>Email</h2>
                        <input type="email" placeholder="some@gmail.com" class="form-control" th:field="*{email}">

                        <h2>Phone Number</h2>
                        <input type="number" id="phone" name="phone" placeholder="89053456237" class="form-control" th:field="*{phone}">

                        <h2>Blood Group</h2>
                        <select class="form-control" id="blood-group" name="blood-group" th:field="*{bloodGroup}">
                            <option value="A+">A+</option>
                            <option value="A-">A-</option>
                            <option value="B+">B+</option>
                            <option value="B-">B-</option>
                            <option value="AB+">AB+</option>
                            <option value="AB-">AB-</option>
                            <option value="O+">O+</option>
                            <option value="O-">O-</option>
                        </select>

                        <h2>Address</h2>
                        <textarea class="textarea" id="" cols="102" rows="3" th:field="*{address}"></textarea>
                        <span th:if="${#fields.hasErrors('address')}" th:errors="*{address}"></span>
                    </div>

                </div>

            </form>


Структура проекта:

5cf253e414289189092783.jpeg

stacktrace ошибок:

2019-06-01 17:16:59.542 ERROR 9332 --- [io-8080-exec-10] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-10] Exception processing template "user/profile": An error happened during template parsing (template: "class path resource [templates/user/profile.html]")

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/user/profile.html]")
	at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
	at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]	
	... 84 common frames omitted
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "user/profile" - line 59, col 95)
	at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]


2019-06-01 17:16:59.547 ERROR 9332 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/user/profile.html]")] with root cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'patient' available as request attribute
	at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
	at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
	at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
	at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
	at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
	at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227) ~[thymeleaf-spring5-3.0.11.RELEASE.jar:3.0.11.RELEASE]
  • Вопрос задан
  • 1392 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы