Problem with controller return statement not performed (about redirect) - spring

I'm working on a side project and it's been delayed for several days. When I run my code, I always can't run it from the "return redirect:/" part of the controller.
The result I expected is that I think of moving from sentence "return redirect:/" to another page, but everything seems fine inside, but only sentence "return redirect:/" is not performed.
I am using Mysql, SpringBoot, JPA, Spring Data Jpa, Lombok. What is the problem?
This is View to receive email and password.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel = "stylesheet" href ="/css/sample.css">
<link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet">
<link href="/css/font.css" rel = "stylesheet">
<link href="/css/navbar.css" rel = "stylesheet">
<title>loginpage</title>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
function functionclick() {
let email = document.getElementById('exampleDropdownFormEmail1').value;
let password = document.getElementById('exampleDropdownFormPassword1').value;
if (email == "" || password == "") {
alert("회원 정보를 입력하세요");
history.back();
} else{
const url = new URL("/trylogin",location);
url.searchParams.append('email',email);
url.searchParams.append('password',password);
location = url;
}
}
</script>
</head>
<body class="p-3 m-0 border-0 bd-example">
<!-- Example Code -->
<div class="dropdown-menu">
<form class="px-4 py-3" method="get" action="login">
<div class="mb-3">
<label for="exampleDropdownFormEmail1" class="form-label">이메일을 입력하세요</label>
<input type="text" class="form-control" id="exampleDropdownFormEmail1" placeholder="email#example.com" name = "email">
</div>
<div class="mb-3">
<label for="exampleDropdownFormPassword1" class="form-label">비밀번호를 입력하세요.</label>
<input type="password" class="form-control" id="exampleDropdownFormPassword1" placeholder="Password" name = "password">
</div>
<div class="mb-3">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="dropdownCheck">
<label class="form-check-label" for="dropdownCheck">
비밀번호 기억하기
</label>
</div>
</div>
<button type="submit" class="btn btn-primary" ONCLICK="functionclick()">확인</button>
</form>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="http://localhost:8080/signup">회원가입 하기</a>
<a class="dropdown-item" href="http://localhost:8080/forgotpassword">비밀번호 찾기</a>
</div>
<!-- End Example Code -->
</body>
</html>
This is LoginController
#Controller
public class LoginController {
#Autowired
private
UserService userService;
#GetMapping("/trylogin")
public String login(LoginDto loginDto) {
try {
if(userService.login(loginDto).isPresent()) {
return "redirect:/loginSuccess";
}
} catch (Exception e) {
e.printStackTrace();
return "redirect:/loginFailed";
}
return "redirect:/loginFailed";
}
#GetMapping("/loginSuccess")
public String loginSuccess() {
return "login_success";
}
#GetMapping("/loginFailed")
public String loginFailed() {
return "login_failed";
}
}
It is a service layer and the Repository used spring data jpa.
#Service
#RequiredArgsConstructor
#Getter
public class UserService {
#Autowired
private UsersRepository usersRepository;
#Transactional
public Optional<Users> login(LoginDto loginDto) throws Exception{
return usersRepository.findByEmailAndPassword(loginDto.getEmail(), loginDto.getPassword());
}
}
This is the Users entity to perform the query.
#Entity
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Table(uniqueConstraints = {#UniqueConstraint(columnNames = {"ssn","phone_number"})})
public class Users {
#Column(name = "email", length = 40, updatable = false, nullable = false)
#Id
private String email;
#Column(name = "password", length = 20, nullable = false)
private String password;
#Column(name = "name", length = 25, nullable = false)
private String name;
#Column(name = "phone_number", length = 12, nullable = false)
private String phoneNumber;
#Column(name = "ssn", length = 13, nullable = false, updatable = false)
private String ssn;
#Embedded
private Address address;
#Column(name = "point")
private Long point;
#OneToMany(mappedBy = "postedUser")
private List<PostInfo> uploadedPost = new ArrayList<>();
#OneToMany(mappedBy = "userId")
private List<PointHistory> pointHistories = new ArrayList<>();
#Embedded
private Dates dates;
public Users(UserInfoDto userInfoDto){
this.setEmail(userInfoDto.getEmail());
this.setPassword(userInfoDto.getPassword());
this.setPhoneNumber(userInfoDto.getPhone_number());
this.setSsn(userInfoDto.getSsn());
this.setPoint(0L);
this.setName(userInfoDto.getName());
Address address = new Address(
userInfoDto.getCity_name(),
userInfoDto.getTown_name(),
userInfoDto.getStreet_name(),
userInfoDto.getZip_code(),
userInfoDto.getDetails()
);
this.setAddress(address);
List<PostInfo> postInfoList = new ArrayList<>();
List<PointHistory> pointHistoryList = new ArrayList<>();
this.setUploadedPost(postInfoList);
this.setPointHistories(pointHistoryList);
Dates dates = new Dates(LocalDateTime.now(), LocalDateTime.now());
this.setDates(dates);
}
public void setEmail(String id) {
this.email = id;
}
public void setPassword(String password) {
this.password = password;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public void setAddress(Address address) {
this.address = address;
}
public void setPoint(Long point) {
this.point = point;
}
public void setUploadedPost(List<PostInfo> uploadedPost) {
this.uploadedPost = uploadedPost;
}
public void setPointHistories(List<PointHistory> pointHistories) {
this.pointHistories = pointHistories;
}
public void setDates(Dates dates) {
this.dates = dates;
}
}
This is LoginDto (To transfer to the controller)
#Getter
#Setter
#AllArgsConstructor
public class LoginDto {
private String email;
private String password;
}
The page for redirection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Success</title>
<script type = "text/javascript">
alert("로그인 성공");
location.href = "/";
</script>
</head>
<body>
</body>
</html>

Related

When I put the list with the specific drugs on the controller I have problem but when I put the name of drugs in mySQL I don't have

2023-01-28 13:55:33.706 WARN 17396 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'patient' on field 'drugs': rejected value [panadol]; codes [typeMismatch.patient.drugs,typeMismatch.drugs,typeMismatch.java.util.Set,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [patient.drugs,drugs]; arguments []; default message [drugs]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Set' for property 'drugs'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'panadol'; nested exception is java.lang.NumberFormatException: For input string: "panadol"]]
package com.example.prescription.model;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
#Entity
#Table(name = "patients")
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "dob")
private String dateOfBirth;
#NotEmpty(message = "Phone number may not be empty")
#Size(min = 10, max = 10)
#Column(name = "phone")
private String phone;
#NotEmpty(message = "Email may not be empty")
#Size(min = 7, max = 50)
#Column(name = "email")
private String email;
#Column(name = "fathers_name")
private String fathersName;
#Column(name = "mothers_name")
private String mothersName;
#Column(name = "amka")
#Size(min = 11, max = 11)
#Pattern(regexp = "^[0-9]+$", message = "AMKA must contain only numbers")
private String amka;
#Column(name = "id_card")
#Pattern(regexp = "^[a-zA-Z0-9]+$", message = "ID must contain only letters and numbers")
private String idCard;
#Column(name = "city")
private String city;
#Column(name = "postal_code")
#Size(min = 5, max = 5)
#Pattern(regexp = "^[0-9]+$", message = "PC must contain only numbers")
private String postalCode;
#Column(name = "symptoms")
private String symptoms;
#Column(name = "pharmacy")
private String pharmacy;
#Column(name = "doctor_name")
private String doctorsName;
#Column(name = "message")
private String message;
#ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE})
#JoinTable(name = "patient_drug",joinColumns = #JoinColumn(name = "patient_id"),
inverseJoinColumns = #JoinColumn(name = "drug_id"))
private Set<Drug> drugs;
public Patient(Patient patient, Drug drug, Date date) {
}
public Patient() {
}
public void addDrug(Drug drug){
this.drugs.add(drug);
drug.getPatients().add(this);
}
public void removeDrug(Drug drug) {
this.drugs.remove(drug);
drug.getPatients().remove(this);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFathersName() {
return fathersName;
}
public void setFathersName(String fathersName) {
this.fathersName = fathersName;
}
public String getMothersName() {
return mothersName;
}
public void setMothersName(String mothersName) {
this.mothersName = mothersName;
}
public String getAmka() {
return amka;
}
public void setAmka(String amka) {
this.amka = amka;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getSymptoms() {
return symptoms;
}
public void setSymptoms(String symptoms) {
this.symptoms = symptoms;
}
public String getPharmacy() {
return pharmacy;
}
public void setPharmacy(String pharmacy) {
this.pharmacy = pharmacy;
}
public String getDoctorsName() {
return doctorsName;
}
public void setDoctorsName(String doctorsName) {
this.doctorsName = doctorsName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Set<Drug> getDrugs() {
return drugs;
}
public void setDrugs(Set<Drug> drugs) {
this.drugs = drugs;
}
public void removeDrugs() {
Iterator<Drug> iterator = this.drugs.iterator();
while (iterator.hasNext()) {
Drug drug = iterator.next();
drug.getPatients().remove(this);
iterator.remove();
}
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Patient patient = (Patient) o;
return Objects.equals(id, patient.id) && Objects.equals(firstName, patient.firstName) && Objects.equals(lastName, patient.lastName) && Objects.equals(dateOfBirth, patient.dateOfBirth) && Objects.equals(phone, patient.phone) && Objects.equals(email, patient.email) && Objects.equals(fathersName, patient.fathersName) && Objects.equals(mothersName, patient.mothersName) && Objects.equals(amka, patient.amka) && Objects.equals(idCard, patient.idCard) && Objects.equals(city, patient.city) && Objects.equals(postalCode, patient.postalCode) && Objects.equals(symptoms, patient.symptoms) && Objects.equals(pharmacy, patient.pharmacy) && Objects.equals(doctorsName, patient.doctorsName) && Objects.equals(message, patient.message) && Objects.equals(drugs, patient.drugs);
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Patient{");
sb.append("id=").append(id);
sb.append(", firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", dateOfBirth='").append(dateOfBirth).append('\'');
sb.append(", phone='").append(phone).append('\'');
sb.append(", email='").append(email).append('\'');
sb.append(", fathersName='").append(fathersName).append('\'');
sb.append(", mothersName='").append(mothersName).append('\'');
sb.append(", amka='").append(amka).append('\'');
sb.append(", idCard='").append(idCard).append('\'');
sb.append(", city='").append(city).append('\'');
sb.append(", postalCode='").append(postalCode).append('\'');
sb.append(", symptoms='").append(symptoms).append('\'');
sb.append(", pharmacy='").append(pharmacy).append('\'');
sb.append(", doctorsName='").append(doctorsName).append('\'');
sb.append(", message='").append(message).append('\'');
sb.append('}');
return sb.toString();
}
}
package com.example.prescription.controller;
import com.example.prescription.model.Drug;
import com.example.prescription.model.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.example.prescription.service.DrugService;
import com.example.prescription.service.PatientService;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#Controller
public class PatientController {
private final PatientService patientService;
private final DrugService drugService;
public PatientController(#Autowired PatientService patientService,
#Autowired DrugService drugService) {
this.patientService = patientService;
this.drugService = drugService;
}
//read
#GetMapping("/allPatients")
public String getAllPatients(Model model) {
List<Patient> patientList = patientService.getAllPatients();
model.addAttribute("patientList", patientList);
return "patients";
}
//edit
#GetMapping("/newPatient")
public ModelAndView register() {
ModelAndView mav = new ModelAndView("patientForm");
mav.addObject("patient", new Patient());
mav.addObject("drugs", drugService.getAllDrugs());
return mav;
}
//save
#PostMapping("/patient/save")
public String savePatient(Patient patient) {
patientService.savePatient(patient);
return "redirect:/allPatients";
}
//update
#GetMapping("/editPatient/{id}")
public ModelAndView editPatient(#PathVariable(value = "id") String id) {
ModelAndView mav = new ModelAndView("patientFormEditToUpdate");
Long pid = Long.parseLong(id);
Patient formPatient = patientService.findPatientById(pid);
mav.addObject("patient", formPatient);
return mav;
}
#PostMapping("/updatePatient/patient/{id}")
public String updatePatient(#PathVariable(value = "id") String id, Patient patient) {
Long pid = Long.parseLong(id);
Patient patient1 = patientService.findPatientById(pid);
patient1 = patient;
patientService.updatePatient(patient1);
return "redirect:/allPatients";
}
//delete
#GetMapping("/delete/{id}")
public String deleteById(#PathVariable(value = "id") String id) {
Long pid = Long.parseLong(id);
Patient deletedPatient = patientService.findPatientById(pid);
patientService.deletePatient(deletedPatient);
return "redirect:/allPatients";
}
#GetMapping("/prescribeDrugs/{id}")
public ModelAndView prescribeDrugs(#PathVariable("id") String id) {
Long pid = Long.parseLong(id);
ModelAndView mav = new ModelAndView("patientFormEdit");
Patient formPatient = patientService.findPatientById(pid);
mav.addObject("patient", formPatient);
mav.addObject("drugs", drugService.getAllDrugs());
mav.addObject("drugList",drugList);
return mav;
}
static List<String> drugList= null;
static{
drugList = new ArrayList<>();
drugList.add("depon");
drugList.add("aspirin");
drugList.add("panadol");
}
#PostMapping("/prescribeDrugs/Patient/{id}")
public String prescribePatientDrugs(#Valid Patient patient,String id, #ModelAttribute(value = "drugs")Long drugId ,BindingResult result)
{
if(result.hasErrors())
{
return "patients";
}
try {
Long pId = Long.parseLong(id);
Patient formPatient = patientService.findPatientById(pId);
Drug drug = drugService.findById(drugId);
formPatient.setCity(patient.getCity());
formPatient.setEmail(patient.getEmail());
formPatient.setPhone(patient.getPhone());
formPatient.setSymptoms(patient.getSymptoms());
formPatient.setPharmacy(patient.getPharmacy());
formPatient.setDoctorsName(patient.getDoctorsName());
formPatient.setMessage(patient.getMessage());
Drug patientDrug= new Drug(patient, drug, new Date());
drugService.save(drug);
formPatient.getDrugs().add(patientDrug);
patientService.updatePatient(formPatient);
}catch (NumberFormatException numberFormatException){
System.out.println("error");
}
return "redirect:/allPatients";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<link th:href="#{/css/webform.css}" href="/css/webform.css" rel="stylesheet" type="text/css"/>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Update Patient</title>
</head>
<script type="text/javascript" th:src="#{/js/webform.js}"></script>
<form th:action="#{/prescribeDrugs/Patient/{id}(id = ${patient.id})}" method="post" th:object="${patient}">
<div class="container prescription-form">
<div class="row">
<div class="col-lg-12 col-12">
<form>
<h1>Electronic Prescription Form</h1>
<div class="row">
<div class="col-lg-6 col-12">
<label>
<span>Patient Name</span><input type="text" th:value="${patient.firstName}"
th:name="firstName" disabled/>
</label>
</div>
<div class="col-lg-6 col-12">
<label>
<span>Patient Email</span><input id="email" type="text" th:value="${patient.email}"
th:name="email"/>
</label>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-12">
<label>
<span>Patient Surname</span><input id="surname" type="text"
th:value="${patient.lastName}" th:name="surname"
disabled/>
</label>
</div>
<div class="col-lg-6 col-12">
<label>
<span>Patient Phone</span><input id="phone" type="text" th:value="${patient.phone}"
th:name="phone"/>
</label>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-12">
<label>
<span>Patient Symptoms</span><input id="symptoms" type="text" th:name="symptoms"
required/>
</label>
<span class="error_message">This field is required</span>
</div>
<span class="error_message">This field is required</span>
</div>
<div class="col-lg-6 col-12" >
<label>
<span>Drug*</span>
<select name="drugs">
<option th:each="drug : ${drugList}"
th:text="${drug}">
</select>
</label>
<span class="error_message">This field is required</span>
</div>
<div class="row">
<div class="col-lg-6 col-12">
<label>
<span>AMKA</span><input id="amka" type="text" th:value="${patient.amka}" th:name="amka"
disabled/>
</label>
</div>
<div class="col-lg-6 col-12">
<label>
<span>Patient ID</span><input id="patient_id" type="text" th:value="${patient.idCard}"
th:name="patient_id" disabled/>
</label>
<span class="error_message">This field is required</span>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-12">
<div class="message pharmacy">
<label class="miniTextfield">
<span>Pharmacy to deliver</span><textarea id="pharmacy" th:name="pharmacy" required></textarea>
</label>
<span class="error_message">This field is required</span>
</div>
</div>
<div class="col-lg-6 col-12">
<div class="message signature">
<label class="miniTextfield">
<span>Doctor Signature</span><textarea id="doctorSignature" th:name="doctorsName" required></textarea>
</label>
<span class="error_message">This field is required</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-12">
<label>
<span>City</span><input id="city" type="text" th:value="${patient.city}" th:name="city"
/>
</label>
</div>
</div>
<div class="message">
<div class="col-lg-12 col-12">
<label class="message_btn_wrapper">
<span>Message</span><textarea id="feedback" th:name="message"></textarea>
<input type="submit" value="Submit Form"/>
<div class="requiredMessage">Fields with * are mandatory</div>
</label>
</div>
</div>
</form>
</div>
</div>
</div>
</form>
In your controller, you are adding a list of Drug objects of type String, and they are not of type Drug. Your Patient is expecting a Set of Drug objects.
You have several other issues in this code too, but create a new Set of Drug objects, either using a constructor directly or using a Builder pattern.
E.g.: like:
Set.of(new Drug("depon"), new Drug("aspirin"), new Drug("panadol"));
But adjusted for your Drug constructor.
Take a look at my public repo for some working code.
https://github.com/vphilipnyc/For_Vasileios_Maziotis

How do I enter a null value in the thymeleaf field of an html page?

I'm making an input page using thymeleaf:
insertText.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/insertText}" th:object="${text}" method="post">
<p th:text="'id: ' + ${text.id}" />
<p th:text="'parent_id' + ${text.parent_id} ?: 'original'" />
<p th:text="'id: ' + ${text.name}" />
<p th:text="'content: ' + ${text.operation}" />
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
And in the parent_it field I want to enter null if it is the original text but I get an error:
Field error in object 'textTable' on field 'parent_id': rejected value [null];
codes [typeMismatch.textTable.parent_id,typeMismatch.parent_id,typeMismatch.java.lang.Integer,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [textTable.parent_id,parent_id]; arguments []; default message [parent_id]];
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'parent_id';
nested exception is java.lang.NumberFormatException: For input string: "null"]]
Although in the post page I added zero value processing:
result.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Result</h1>
<p th:text="'id: ' + ${text.id}" />
<p th:text="'content: ' + ${text?.parent_id}" />
<p th:text="'id: ' + ${text.name}" />
<p th:text="'content: ' + ${text.operation}" />
Submit another message
</body>
</html>
Maybe there is a way to make this possible?
My entity
textTablt
package com.example.HiberTest.Entities;
#Entity
#Table(name = "textTable")
public class textTable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "parent_id")
private Integer parent_id;
#NotBlank
#Size(min=1, max=128)
#Column(name = "name")
private String name;
#NotBlank
#Size(min=1, max=128)
#Column(name = "operation")
private String operation;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParent_id() {
return parent_id;
}
public void setParent_id(Integer parent_id) {
this.parent_id = parent_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
#Override
public String toString(){
return String.format("id = %o" +
", parent_id = %o, " +
"name = %s, operation = %s ",
id,parent_id,name,operation);
}
}
My conroller:
package com.example.HiberTest.Controller;
import java.util.List;
#Controller
public class TextController {
#Autowired
daoRepository dao;
#GetMapping("/insertText")
public String insertText(Model model){
//List<textTable> list =dao.findAll();
//model.addAttribute("texts",list);
model.addAttribute("text", new textTable());
return "insertText";
}
#PostMapping("/insertText")
public String getAllText(#ModelAttribute textTable texts, Model model){
//List<textTable> list =dao.findAll();
model.addAttribute("text", texts);
return "result";
}
}
I would be glad of help to figure out how to enter a null value so that it is processed correctly
Your variable parent_id in class textTable is of type Integer but you are trying to insert string in it. you are trying to append integer id in string 'parent_id' and then store in Database that's why you are getting error.

Not mapping all fields from html to controller

I need to update my category object
my model:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
#Entity
public class Category {
#Id
#GeneratedValue
private int id;
#NotNull
private String name;
private String description;
#NotNull
private Long created;
private Long updated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCreated() {
return created;
}
public void setCreated(Long created) {
this.created = created;
}
public Long getUpdated() {
return updated;
}
public void setUpdated(Long updated) {
this.updated = updated;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
Here my controller:
#Controller
public class CategoryController {
private CategoryRepository categoryRepository;
private static Logger logger = LogManager.getLogger(CategoryController.class);
// If class has only one constructore then #Autowired wiil execute automatically
public CategoryController(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
createStubCategoryList();
}
#PostMapping(value = "/category")
public String submitCategory(Category category, Model model) {
logger.info("updateCategory = " + category);
model.addAttribute("submitted", true);
model.addAttribute("category", category);
categoryRepository.save(category);
return "category";
}
#RequestMapping("category/edit/{id}")
public String editCategory(#PathVariable("id") int id, Model model) {
Optional<Category> category = categoryRepository.findById(id);
logger.info("find_category = " + category);
model.addAttribute("category", category);
return "category";
}
Here my template to edit category:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${appName}">Category template title</title>
<link th:href="#{/public/style.css}" rel="stylesheet"/>
<meta charset="UTF-8"/>
</head>
<body>
<div class="container">
<form method="post" action="#" th:object="${category}" th:action="#{/category}">
<h3>Category</h3>
<input type="text" placeholder="name" id="name" th:field="*{name}"/>
<textarea placeholder="Description of the category" rows="5" id="description"
th:field="*{description}"></textarea>
<input type="submit" value="Submit"/>
</form>
<div class="result_message" th:if="${submitted}">
<h3>Your category has been submitted.</h3>
<p>Find all categories here</p>
</div>
</div>
</body>
</html>
When call method in log has:
[INFO ] 2020-01-07 19:38:07.493 [http-nio-8090-exec-8] CategoryController - find_category = Optional[
Category{id=2, name='Electronics', created=1578418669105, updated=null, description='Electronics's description'}]
and here screen:
As you can see the field created=1578418669105
Nice.
Now I edit name "Electronics" to "Electronics2" and click submit.
As result call method: submitCategory in my controller. Nice.
Here result in log:
[INFO ] 2020-01-07 19:40:23.327 [http-nio-8090-exec-2] CategoryController - updateCategory =
Category{id=0, name='Electronics2', created=null, updated=null, description='Electronics's description'}
but as you can see the field created is null. Why?
I need to update only editable fields: name and description.
Another fields (like created, updated, id) must not change. This fields are not mapped.
How I can do this?
Because created, updated, id you need to pass as hidden. It is not available in html page.
Each column should be changed to updatable to false because by default is true.
#Column(name = "created", updatable = false)
private Long created;

Spring MVC test failure

I'm writing simple integration tests for my app using the Spring MVC Test framework. I have two basic test cases:
The Add link form is filled in correctly (the URL and optional description input fields are entered) and a link is added to a database via POST and then the client is redirected to the /link URL.
The Add link form is empty, so the /links/create view is rendered and form errors from BindingResult are presented.
The testAddLink() test passes successfully, but the problem occurs with the testAddEmptyLink() test method.
In this test, the 'links/create' view should be rendered and I should get a 200 status code once the expression
result.hasErrors()
is true.
However, I'm getting a 302 response, which should be sent when there are no errors in the form (the URL has been set correctly)
It seems the test method testAddEmptyLink() cannot deal with form errors with BindingResult.
Do you have any ideas what could be the cause it cannot deal with form errors?
Thanks in advance.
Link Entity
#Entity
#Table(name = "links")
public class Link {
#Id #GeneratedValue
private Integer ID;
#Column(name = "url") #NotNull #NotEmpty #URL
private String URL;
private String description;
#Column(name="created_at", nullable = false)
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime createdAt;
#Column(name="updated_at", nullable = true)
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime updatedAt;
#ManyToOne
#JoinColumn(name = "category_id")
private Category category;
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdateddAt() {
return updatedAt;
}
public void setUpdateddAt(LocalDateTime updateddAt) {
this.updatedAt = updateddAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
LinkController
#Controller
public class LinkController {
#Autowired(required = true) #Qualifier(value = "linkService")
private LinkService linkService;
#Autowired
private CategoryService categoryService;
#RequestMapping(value = "/links")
public String getLinks(Model model) {
model.addAttribute("results", linkService.getLinks());
return "links/index";
}
#RequestMapping(value = "/links/create", method = RequestMethod.GET)
public ModelAndView showLinkForm() {
ModelAndView model = new ModelAndView("links/create");
model.addObject("link", new Link());
model.addObject("categories", categoryService.getCategories());
return model;
}
#RequestMapping(value = "/links/create", method = RequestMethod.POST)
public String addLink(#Valid #ModelAttribute("link") Link link, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute("categories", categoryService.getCategories());
return "links/create";
}
linkService.addLink(link);
return "redirect:/links";
}
}
LinkControllerTest
#ContextConfiguration(classes = {AppInitializer.class})
#RunWith(SpringJUnit4ClassRunner.class)
public class LinkControllerTest {
#Mock
private LinkService linkService;
#InjectMocks
private LinkController linkController;
private MockMvc mockMvc;
#Before
public void setUp() {
// Process mock annotations
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(linkController).build();
}
#Test
public void testAddLink() throws Exception {
mockMvc.perform(post("/links/create")
.param("URL", "http://test.com")
.param("description", "Lorem Ipsum")
.param("category.ID", "1"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/links"));
}
#Test
public void testAddEmptyLink() throws Exception {
mockMvc.perform(post("/links/create")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.sessionAttr("link", new Link())
)
.andExpect(status().isOk())
.andExpect(view().name("links/create"))
.andExpect(forwardedUrl("/WEB-INF/views/links/create.jsp"))
.andExpect(model().attributeHasFieldErrors("link", "URL", "description"))
.andExpect(model().attribute("link", hasProperty("URL", isEmptyOrNullString())))
.andExpect(model().attribute("link", hasProperty("description", isEmptyOrNullString())));
}
}
create.jsp (View)
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Create Category</title>
</head>
<body>
<form:form action="" modelAttribute="category">
<div>
<form:label path="name">Name</form:label>
<form:input path="name" />
<form:errors path="name" cssClass="error"></form:errors>
</div>
<div>
<form:label path="description">Description</form:label>
<form:input path="description" />
<form:errors path="description" cssClass="error"></form:errors>
</div>
<div>
<input type="submit" value="Create Category">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</div>
</form:form>
</body>
</html>

Spring MVC webapp HTTP Status 400

Im developing a webapp with Spring and hibernate. I have a simple form with a text field and a select:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=utf8" pageEncoding="utf8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page trimDirectiveWhitespaces="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Content-Language" content="English"/>
<!-- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Language" content="es"/>-->
<link rel="stylesheet" media="all" href="<c:url value="/resources/site.css"/>">
<title>Nuevo expediente</title>
</head>
<body>
<h2>Nuevo expediente</h2>
<form:form modelAttribute="expediente" method="post">
<table>
<tr>
<td>Tipo de expediente:</td>
<td>
<form:select path="tipoExpediente">
<form:option value="-" label="Seleccione un tipo"/>
<form:options items="${expedientes}" itemValue="tipoExpediente" itemLabel="tipoExpediente" />
</form:select>
<form:errors path="tipoExpediente" element="span"/>
</td>
</tr>
<tr>
<td>Estado:</td>
<td>
<form:input path="estado"/>
<form:errors path="estado" element="span"/>
</td>
</tr>
</table>
<br/>
<input type="submit" value="Create" />
</form:form>
</body>
</html>
The form show correctly, but when i submit, I get a HTTP Status 400 exception, with the description:
description The request sent by the client was syntactically incorrect ()..
I have read that it would be caused by requestparams, but i not using them.
Here is my controller:
package com.atlantis.atecliente.controller;
import com.atlantis.atecliente.model.Book;
import com.atlantis.atecliente.model.Expediente;
import com.atlantis.atecliente.model.TipoExpediente;
import com.atlantis.atecliente.repository.ExpedienteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ExpedienteController {
#Autowired
protected ExpedienteService service;
#RequestMapping(value = {"/*", "/expedientes"})
public String getExpedientes(Model model) {
List<Expediente> expedientes = service.getExpedientes();
model.addAttribute("expedientes", expedientes);
return "expediente";
}
#RequestMapping(value = "nuevo-expediente")
public String createExpedienteGet(Model model) {
model.addAttribute("expediente", new Expediente());
List<TipoExpediente> tiposExpediente = service.getTiposExpedientes();
// List<String> canales = service.getCanales();
model.addAttribute("expedientes", tiposExpediente);
// model.addAttribute("canales", canales);
return "nuevo-expediente";
}
#RequestMapping(value = "nuevo-expediente", method = RequestMethod.POST)
public String createExpedientePost(#ModelAttribute("expediente") Expediente expediente) {
service.createExpediente(expediente);
return "redirect:expedientes";
}
}
Finalyy the Expediente class:
package com.atlantis.atecliente.model;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="Expediente")
public class Expediente {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int codExpediente;
#ManyToOne
#JoinColumn(name = "tipoExpediente")
private TipoExpediente tipoExpediente;
#ManyToOne
#JoinColumn(name = "estadoExpediente")
private EstadoExpediente estadoExpediente;
#ManyToOne
#JoinColumn(name = "expedientePadre")
private Expediente expedientePadre;
#ManyToOne
#JoinColumn(name = "tipoRelacion")
private TipoRelacion tipoRelacion;
#ManyToOne
#JoinColumn(name = "canalEntrada")
private CanalExpediente canalEntrada;
#ManyToOne
#JoinColumn(name = "idiomaEntrada")
private IdiomaExpediente idiomaEntrada;
#ManyToOne
#JoinColumn(name = "idiomaSalida")
private IdiomaExpediente idiomaSalida;
#ManyToOne
#JoinColumn(name = "tipoResolucion")
private TipoResolucion tipoResolucion;
#ManyToOne
#JoinColumn(name = "canalSalida")
private CanalExpediente canalSalida;
#Column(length = 30)
private String estado;
#Column(length = 10)
private String numeroSerie;
#Column(length = 10)
private String numeroHoja;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaRedaccion;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaRecepcion;
#Column(length = 200)
private String asunto;
#Column (length = 1000)
private String descripcion;
#Column(length = 20)
private String usuarioRegistro;
#Temporal(javax.persistence.TemporalType.DATE)
private Date fechaRegistro;
#Column (length = 20)
private String usuarioModificacion;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaModificacion;
#Column (length = 20)
private String usuarioCierre;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaCierre;
public int getCodExpediente() {
return codExpediente;
}
public void setCodExpediente(int codExpediente) {
this.codExpediente = codExpediente;
}
public EstadoExpediente getEstadoExpediente() {
return estadoExpediente;
}
public void setEstadoExpediente(EstadoExpediente estadoExpediente) {
this.estadoExpediente = estadoExpediente;
}
public Expediente getExpedientePadre() {
return expedientePadre;
}
public void setExpedientePadre(Expediente expedientePadre) {
this.expedientePadre = expedientePadre;
}
public TipoRelacion getTipoRelacion() {
return tipoRelacion;
}
public void setTipoRelacion(TipoRelacion tipoRelacion) {
this.tipoRelacion = tipoRelacion;
}
public CanalExpediente getCanalEntrada() {
return canalEntrada;
}
public void setCanalEntrada(CanalExpediente canalEntrada) {
this.canalEntrada = canalEntrada;
}
public IdiomaExpediente getIdiomaEntrada() {
return idiomaEntrada;
}
public void setIdiomaEntrada(IdiomaExpediente idiomaEntrada) {
this.idiomaEntrada = idiomaEntrada;
}
public IdiomaExpediente getIdiomaSalida() {
return idiomaSalida;
}
public void setIdiomaSalida(IdiomaExpediente idiomaSalida) {
this.idiomaSalida = idiomaSalida;
}
public TipoResolucion getTipoResolucion() {
return tipoResolucion;
}
public void setTipoResolucion(TipoResolucion tipoResolucion) {
this.tipoResolucion = tipoResolucion;
}
public CanalExpediente getCanalSalida() {
return canalSalida;
}
public void setCanalSalida(CanalExpediente canalSalida) {
this.canalSalida = canalSalida;
}
public String getUsuarioRegistro() {
return usuarioRegistro;
}
public void setUsuarioRegistro(String usuarioRegistro) {
this.usuarioRegistro = usuarioRegistro;
}
public String getNumeroSerie() {
return numeroSerie;
}
public void setNumeroSerie(String numeroSerie) {
this.numeroSerie = numeroSerie;
}
public String getNumeroHoja() {
return numeroHoja;
}
public void setNumeroHoja(String numeroHoja) {
this.numeroHoja = numeroHoja;
}
public Date getFechaRedaccion() {
return fechaRedaccion;
}
public void setFechaRedaccion(Date fechaRedaccion) {
this.fechaRedaccion = fechaRedaccion;
}
public Date getFechaRecepcion() {
return fechaRecepcion;
}
public void setFechaRecepcion(Date fechaRecepcion) {
this.fechaRecepcion = fechaRecepcion;
}
public String getAsunto() {
return asunto;
}
public void setAsunto(String asunto) {
this.asunto = asunto;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Date getFechaRegistro() {
return fechaRegistro;
}
public void setFechaRegistro(Date fechaRegistro) {
this.fechaRegistro = fechaRegistro;
}
public String getUsuarioModificacion() {
return usuarioModificacion;
}
public void setUsuarioModificacion(String usuarioModificacion) {
this.usuarioModificacion = usuarioModificacion;
}
public Date getFechaModificacion() {
return fechaModificacion;
}
public void setFechaModificacion(Date fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
public String getUsuarioCierre() {
return usuarioCierre;
}
public void setUsuarioCierre(String usuarioCierre) {
this.usuarioCierre = usuarioCierre;
}
public Date getFechaCierre() {
return fechaCierre;
}
public void setFechaCierre(Date fechaCierre) {
this.fechaCierre = fechaCierre;
}
public TipoExpediente getTipoExpediente() {
return tipoExpediente;
}
public void setTipoExpediente(TipoExpediente tipoExpediente) {
this.tipoExpediente = tipoExpediente;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
Some help?
Thanks
I have resolve this issue. The problem was with the controller method mapping to the url.
I modified the function createExpedientePost to:
public String createExpedientePost(#ModelAttribute("expediente") Expediente expediente, BindingResult result) {
The change was the addition of BindingResult as an argument.
I hope this may help others.
It seems somebody can get such error status, when arguments for a controller method were set incorrectly.
For instance I had the same because of wrong name of referer header(It was called as referrer)
public String foo(#RequestHeader(value = "referer") final String referer) {}

Resources