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 - spring-boot

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

Related

Problem with controller return statement not performed (about redirect)

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>

How to populate dropdown list from one entity class to another in spring-boot?

Customer.java file
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String relative;
private String address;
private Long aadhar;
private Long contact;
public Long getAadhar() {
return aadhar;
}
public void setAadhar(Long aadhar) {
this.aadhar = aadhar;
}
#ManyToOne
#JoinColumn(name="town_name",insertable = false,updatable = false)
private Town town;
private String town_name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRelative() {
return relative;
}
public void setRelative(String relative) {
this.relative = relative;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Town getTown() {
return town;
}
public void setTown(Town town) {
this.town = town;
}
public String getTown_name() {
return town_name;
}
public void setTown_name(String town_name) {
this.town_name = town_name;
}
public Long getContact() {
return contact;
}
public void setContact(Long contact) {
this.contact = contact;
}
}
Town.Java
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Town {
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Id
private String townname;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTownname() {
return townname;
}
public void setTownname(String townname) {
this.townname = townname;
}
}
CustomerController.java file
#Controller
public class CutomerController {
#Autowired
private CutomerService customerService;
#GetMapping("/customer")
public String findAllCustomers(Model model) {
model.addAttribute("customers", customerService.findAllCustomers());
return "customer";
}
#PostMapping("/customer/addnew")
public String addNew(Customer customer) {
customerService.saveCustomer(customer);
return "redirect:/customer";
}
}
TownController.java file
#Controller
public class TownController {
#Autowired
private TownService townService;
#GetMapping("/town")
public String findAllTowns(Model model) {
model.addAttribute("towns", townService.findAllTown());
return "town";
}
}
My customer.html file
<!-- Multi Columns Form -->
<form class="row g-3" th:action="#{/customer/addnew}" method="post">
<div class="col-md-4">
<label for="aadhar" class="form-label">Aadhar No.</label>
<input type="number" min="0" max="999999999999" class="form-control" id="aadhar">
</div>
<div class="col-md-8">
<label for="customername" class="form-label">Customer Name</label>
<input type="text" class="form-control" id="name"onKeyup="this.value = this.value.toUpperCase()" required>
</div>
<div class="col-md-6">
<label for="relative" class="form-label">S/O,D/O,C/O</label>
<input type="text" class="form-control" id="relative"onKeyup="this.value = this.value.toUpperCase()" required>
</div>
<div class="col-md-6">
<label for="contact" class="form-label">Contact No.</label>
<input type="number" max="9999999999" class="form-control" id="contact">
</div>
<div class="col-12">
<label for="inputAddress5" class="form-label">Address</label>
<input type="text" class="form-control" id="address"onKeyup="this.value = this.value.toUpperCase()" placeholder="1234 Main St" required>
</div>
<div class="col-md-4">
<label for="inputTown" class="form-label" id="selecttown">Town/Area</label>
<select class="form-control" id="selecttown" name="townname" th:field="*{townname}" required>
<option selected>Choose...</option>
<option th:each="town:${towns}" th:value="${town.towname}" th:text="${town.towname}"></option>
</select>
</div>
<div class="text-center" style="margin-bottom:10px">
<button type="submit" class="btn btn-primary mx-1 my-1">Submit</button>
i am expecting populate the names of towns in dropdown list of customer modal form. But i am getting this error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Nov 30 12:18:23 IST 2022
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/customer.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/customer.html]")
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring6.processor.SpringSelectFieldTagProcessor' (template: "customer" - line 473, col 70)
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring6.processor.SpringSelectFieldTagProcessor' (template: "customer" - line 473, col 70)
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'townname' available as request attribute
Your are referencing wrong variable.
Modify your CustomerController class like this:
#Autowired
private CutomerService customerService;
#Autowired
private TownService townService;
#GetMapping("/customer")
public String findAllCustomers(Model model) {
model.addAttribute("customers", customerService.findAllCustomers());
model.addAttribute("towns", townService.findAllTown());
return "customer";
}
#PostMapping("/customer/addnew")
public String addNew(Customer customer) {
customerService.saveCustomer(customer);
return "redirect:/customer";
}

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;

There was an unexpected error (type=Not Found, status=404). No message available : spring+ thymeleaf

i'm creating a formular to add a product_status in PostgreSql database , but i'm stacked in this erros; i think that i'm not able to send Bigdecimal value in because in the class StatusProduits the type of id is Bigdecimal, so i'm not able to add statusProduct in database because the input type dont match with the type of the ID of status_product...
this is the class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.demo.entities;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* #author G557437
*/
#Entity
#Table(name = "STATUT_PRODUITS", catalog = "", schema = "PACKOUT")
#NamedQueries({
#NamedQuery(name = "StatutProduits.findAll", query = "SELECT s FROM StatutProduits s")})
public class StatutProduits implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#NotNull
#Column(name = "ID_STATUT_PRODUIT")
private BigDecimal idStatutProduit;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "CODE")
private String code;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "LIBELLE")
private String libelle;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "CREE_PAR")
private String creePar;
#Column(name = "DATE_CREATION")
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreation;
#Size(max = 10)
#Column(name = "MAJ_PAR")
private String majPar;
#Column(name = "DATE_MAJ")
#Temporal(TemporalType.TIMESTAMP)
private Date dateMaj;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "idStatutProduit")
private List<Produits> produitsList;
public StatutProduits() {
}
public StatutProduits(BigDecimal idStatutProduit) {
this.idStatutProduit = idStatutProduit;
}
public StatutProduits(BigDecimal idStatutProduit, String code, String libelle, String creePar) {
this.idStatutProduit = idStatutProduit;
this.code = code;
this.libelle = libelle;
this.creePar = creePar;
}
public BigDecimal getIdStatutProduit() {
return idStatutProduit;
}
public void setIdStatutProduit(BigDecimal idStatutProduit) {
this.idStatutProduit = idStatutProduit;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public String getCreePar() {
return creePar;
}
public void setCreePar(String creePar) {
this.creePar = creePar;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public String getMajPar() {
return majPar;
}
public void setMajPar(String majPar) {
this.majPar = majPar;
}
public Date getDateMaj() {
return dateMaj;
}
public void setDateMaj(Date dateMaj) {
this.dateMaj = dateMaj;
}
public List<Produits> getProduitsList() {
return produitsList;
}
public void setProduitsList(List<Produits> produitsList) {
this.produitsList = produitsList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idStatutProduit != null ? idStatutProduit.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof StatutProduits)) {
return false;
}
StatutProduits other = (StatutProduits) object;
if ((this.idStatutProduit == null && other.idStatutProduit != null) || (this.idStatutProduit != null && !this.idStatutProduit.equals(other.idStatutProduit))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.sagemcom.tn.entities.StatutProduits[ idStatutProduit=" + idStatutProduit + " ]";
}
}
the controller :
package com.example.demo.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.demo.dao.StatutProduitsRepository;
import com.example.demo.entities.StatutProduits;
#Controller
public class StatutProduitsController {
#Autowired
StatutProduitsRepository statutproduitsrepository ;
#RequestMapping(value="/index")
public String index( Model model,
#RequestParam(name="page", defaultValue="0")int p,
#RequestParam(name="size", defaultValue="3")int s)
{
Page<StatutProduits> pagestatutsproduits = statutproduitsrepository.findAll(new PageRequest(p,s));
model.addAttribute("listStatutProduits",pagestatutsproduits.getContent());
int [] pages = new int [pagestatutsproduits.getTotalPages()];
model.addAttribute("pages",pages);
model.addAttribute("size",s);
model.addAttribute("pageCourante",p);
return "statutproduits" ;
}
#RequestMapping(value="/form", method=RequestMethod.GET)
public String save( Model model,StatutProduits statproduit) {
statutproduitsrepository.save(statproduit);
return "Confirmation";
}
}
the HTML page :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css"
href="../static/css/bootstrap.min.css"
th:href="#{css/bootstrap.min.css}"
/>
<title>Statut du produit</title>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Statut d'un produit</div>
<div class="panel-body">
<form th:action="#{save}" method="post">
<div class="form-group">
<label class="control-label">ID</label>
<input class="form-control" type="number" name="id"
th:value="${statproduit.idStatutProduit}"/>
</div>
<div class="form-group">
<label class="control-label">Code</label>
<input class="form-control" type="text" name="code"
th:value="${statproduit.code}"/>
</div>
<div class="form-group">
<label class="control-label">Cree par</label>
<input class="form-control" type="text" name="creePar"
th:value="${statproduit.creePar}"/>
</div>
<div class="form-group">
<label class="control-label">Date creation</label>
<input class="form-control" type="date" name="dateCreation"
th:value="${statproduit.dateCreation}"/>
</div>
<div class="form-group">
<label class="control-label">Date maj</label>
<input class="form-control" type="date" name="DateMaj"
th:value="${statproduit.dateMaj}"/>
</div>
<div class="form-group">
<label class="control-label">Libelle</label>
<input class="form-control" type="text" name="libelle"
th:value="${statproduit.libelle}"/>
</div>
<div class="form-group">
<label class="control-label">Maj par</label>
<input class="form-control" type="text" name="majPar"
th:value="${statproduit.majPar}"/>
</div>
<div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>

Cannot update my form in spring boot

My model is
#Entity
#Table(name = "sls_notifications")
public class SLSNotification {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(length = 11)
private Integer snumber;
#JsonFormat(pattern="yyyy-MM-dd")
#Column(nullable = false)
private Date date = new Date();
#Column(length = 8)
private String cusOffice;
#Column(length = 1)
private String cusSerial;
#Column(length = 50)
private String cusDecNo;
#JsonFormat(pattern="yyyy-MM-dd")
private Date cusDate;
#Column(length = 300)
private String manufacturer;
#Column(length = 300)
private String exporterAddress;
#Column(length = 20)
private String importerVAT;
#NotEmpty
#Column(length = 20, nullable = false)
private String declarantVAT;
private String declarantDetails;
private String vessel;
private String blNo;
private String loadingPort;
private String tradingCountry;
private String countryOrigin;
private String invoiceNo;
#JsonFormat(pattern="yyyy-MM-dd")
private Date invoiceDate;
private Double invoiceValue;
private String uom;
private Double totalQty;
private String marksNumber;
private String goodsDesc;
private String purpose;
private String hsCode;
private String issuerQltyCert;
private String qltyCertifacateNo;
private String slsNo;
private String invoiceLoc;
private String blLoc;
private String packlistLoc;
private String qcLoc;
private String otherLoc;
private String accRep;
private String accRepLoc;
#NotEmpty
#Column(length = 255, nullable = false)
private String status = "PENDING";
private String userId;
private String slsiUnit;
private String importerDetails;
private String productDesc;
private String certRefNo;
#JsonFormat(pattern="yyyy-MM-dd")
private Date blDate;
private String loadCountry;
}
My repositary is
public interface SLSNotificationRepository extends
CrudRepository<SLSNotification, Integer> {
#Override
SLSNotification save(SLSNotification slsNotification);
#Override
SLSNotification findOne(Integer snumber);
#Override
long count();
#Override
void delete(Integer integer);
#Override
void delete(SLSNotification slsNotification);
#Override
void delete(Iterable<? extends SLSNotification> iterable);
#Override
List<SLSNotification> findAll();
#Query("select a from SLSNotification a where a.slsiUnit in :unitList")
List<SLSNotification> getApplicationsByUnit(#Param("unitList")List <String> unitList);
#Query("select a from SLSNotification a where a.userId = :userId")
List<SLSNotification> getApplicationsByUserId(#Param("userId")String userId);
#Query("select a from SLSNotification a where a.slsNo = :slsNo")
SLSNotification getApplicationBySLSNumber(#Param("slsNo") String slsNo);
#Query("select a from SLSNotification a where a.importerVAT = :importerVAT group by slsNo")
List<SLSNotification> getproductByUserId(#Param("importerVAT")String importerVAT);
}
My services is
package lk.slsi.services;
import lk.slsi.domain.SLSNotification;
import lk.slsi.repository.SLSIWorkflowRepository;
import lk.slsi.repository.SLSNotificationRepository;
import lk.slsi.storage.FileSystemStorageService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import org.springframework.data.repository.query.Param;
#Service
#Scope("session")
public class ApplicationServices {
private static final Logger serviceLogger = LogManager.getLogger(ApplicationServices.class);
#Autowired
private SLSNotificationRepository slsNotificationRepository;
#Autowired
private WorkflowServices workflowServices;
#Autowired
private FileSystemStorageService storageService;
#Autowired
private FileUploadRollBack rollBack;
#Value("${slsi.filePaths.packlist}")
private String packlist;
#Value("${slsi.filePaths.qc}")
private String qc;
#Value("${slsi.filePaths.bl}")
private String bl;
#Value("${slsi.filePaths.invoice}")
private String invoice;
#Value("${slsi.filePaths.otherDoc}")
private String otherDoc;
#Value("${slsi.filePaths.accept}")
private String accept;
public boolean updateOrAddApplication(SLSNotification slsNotification,
MultipartFile attachInv,
MultipartFile attachBL,
MultipartFile attachPackList,
MultipartFile attachQc,
MultipartFile attachOther,
MultipartFile fileAccRep) {
serviceLogger.info("Staring adding/updating the SLS Notification data . data : [{}]", slsNotification);
try {
if (!attachInv.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachInv.getOriginalFilename());
slsNotification.setInvoiceLoc(storageService.store(attachInv, invoice));
rollBack.addRollbackPoint(invoice,slsNotification.getInvoiceLoc());
}
if (!attachBL.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachBL.getOriginalFilename());
slsNotification.setBlLoc(storageService.store(attachBL, bl));
rollBack.addRollbackPoint(bl,slsNotification.getBlLoc());
}
if (!attachPackList.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachPackList.getOriginalFilename());
slsNotification.setPacklistLoc(storageService.store(attachPackList, packlist));
rollBack.addRollbackPoint(packlist,slsNotification.getPacklistLoc());
}
if (!attachQc.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachQc.getOriginalFilename());
slsNotification.setQcLoc(storageService.store(attachQc, qc));
rollBack.addRollbackPoint(qc,slsNotification.getQcLoc());
}
if (!attachOther.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", attachOther.getOriginalFilename());
slsNotification.setOtherLoc(storageService.store(attachOther, otherDoc));
rollBack.addRollbackPoint(otherDoc,slsNotification.getOtherLoc());
}
if (!fileAccRep.isEmpty()) {
serviceLogger.info("Uploading file : [{}]", fileAccRep.getOriginalFilename());
slsNotification.setAccRepLoc(storageService.store(fileAccRep, accept));
rollBack.addRollbackPoint(accept,slsNotification.getAccRepLoc());
}
serviceLogger.info("Saving data in the database. [{}]", slsNotification);
slsNotificationRepository.save(slsNotification);
workflowServices.initWorkflow(slsNotification.getSnumber());
return true;
} catch (Exception e) {
serviceLogger.error("Error occurred while saving SLS Common data . [{}]", e);
rollBack.rollback();
return false;
}
}
public boolean update(SLSNotification slsNotification) {
serviceLogger.info("Staring adding/updating the SLS Notification data . data : [{}]", slsNotification);
try {
serviceLogger.info("Saving data in the database. [{}]", slsNotification);
slsNotificationRepository.save(slsNotification);
return true;
} catch (Exception e) {
serviceLogger.error("Error occurred while saving SLS Common data . [{}]", e);
rollBack.rollback();
return false;
}
}
public List<SLSNotification> getAll(){
return slsNotificationRepository.findAll();
}
public SLSNotification getSLSNotificationBySerialNumnber(Integer serialNumber) {
return slsNotificationRepository.findOne(serialNumber);
}
public List<SLSNotification> getApplicationsByUserId(String userId){
return slsNotificationRepository.getApplicationsByUserId(userId);
}
public List<SLSNotification> getproductByUserId(String importerVAT){
return slsNotificationRepository.getproductByUserId(importerVAT);
}
public List<SLSNotification> getApplicationsByUnit(List <String> unitList){
return slsNotificationRepository.getApplicationsByUnit(unitList);
}
public SLSNotification getApplicationById(Integer snumber){
return slsNotificationRepository.findOne(snumber);
}
public Resource getFile(String filename){
return storageService.getFileResource(filename);
}
}
My controller is
package lk.slsi.controller;
import lk.slsi.domain.SLSNotification;
import lk.slsi.exceptions.ProductWithSameSerialExistsException;
import lk.slsi.security.domain.AuthenticatedUser;
import lk.slsi.services.ApplicationServices;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.SimpleFileResolver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import static org.hibernate.annotations.common.util.impl.LoggerFactory.logger;
/**
* Created by ignotus on 2/18/2017.
*/
#Controller
#RequestMapping(path = "/")
#Scope("session")
public class ApplicationUrlMapController {
private static final Logger slsiLogger = LogManager.getLogger(ApplicationUrlMapController.class);
private static final String MESSAGE_KEY = "message";
private static final String APPLICATION_REDIRECT = "redirect:/application";
#Autowired
private ServletContext servletContext;
#Autowired
private ApplicationServices applicationServices;
#Autowired
private ProductServices productServices;
private MailService mailservice;
#Autowired
private ManufacturerServices manufacturerServices;
#Autowired
private WorkflowServices workflowServices;
#Value("${slsi.reportData}")
private String reportDataLocation;
#RequestMapping(path = "/application")
public String viewApplication(Model model) {
model.addAttribute("manu", manufacturerServices.getManufacturerListbyStatus());
model.addAttribute("edit", true);
return "application";
}
#RequestMapping(path = "/EditApplication/{snumber}",method = RequestMethod.POST)
public String addApplication(#PathVariable("snumber") #ModelAttribute("snumber") String snumber, Model model) {
model.addAttribute("app", applicationServices.getApplicationById(Integer.parseInt(snumber)));
model.addAttribute("manu", manufacturerServices.getManufacturerListbyStatus());
model.addAttribute("edit", true);
return "editApplication";
}
#RequestMapping(path = "/executeApplication", method = RequestMethod.POST)
public String registerApplication(#ModelAttribute("applicationForm") #Valid SLSNotification application,
BindingResult result,
HttpSession session,
#RequestParam("attachInv") MultipartFile attachInv,
#RequestParam("attachBL") MultipartFile attachBL,
#RequestParam("attachPackList") MultipartFile attachPackList,
#RequestParam("attachQc") MultipartFile attachQc,
#RequestParam("attachOther") MultipartFile attachOther,
#RequestParam("fileAccRep") MultipartFile fileAccRep) {
if (result.hasErrors()) {
session.setAttribute(MESSAGE_KEY, "application validation failed");
return "redirect:/application?" + MESSAGE_KEY;
}
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal != null && principal instanceof AuthenticatedUser) {
AuthenticatedUser auth = (AuthenticatedUser) principal;
application.setUserId(String.valueOf(auth.getUserId()));
}
//Setting the slsiUnit of the notification
// String sls = application.getSlsNo();
// Product p = productServices.getProductBySlsNo(Integer.parseInt(sls));
// int slsUnitNumber =p.getSlsiUnit();
//
// application.setSlsiUnit("UNIT"+ slsUnitNumber);
slsiLogger.info("Executing application update. application : [{}]", application);
if (applicationServices.updateOrAddApplication(application,
attachInv, attachBL, attachPackList, attachQc, attachOther, fileAccRep)) {
session.setAttribute(MESSAGE_KEY, "application update successful!");
} else {
session.setAttribute(MESSAGE_KEY, "application update was not successful");
}
return "redirect:/applicationManage?" + MESSAGE_KEY;
}
#RequestMapping(path = "/updateUserApplication", method = RequestMethod.POST)
public String updateApplication(#ModelAttribute("updateapplicationForm") #Valid SLSNotification slsNotification,
BindingResult result,
HttpSession session) {
slsiLogger.info("Request received to register new product. [{}]", slsNotification);
if (result.hasErrors()) {
slsiLogger.error("Rejecting the request due to binding errors, [{}]", result.getFieldErrors());
return "redirect:/applicationManage?";
}
if (applicationServices.update(slsNotification)) {
slsiLogger.info("Product registered successfully");
session.setAttribute(MESSAGE_KEY, "Product registered successfully");
} else {
session.setAttribute(MESSAGE_KEY, "Error occurred while registering the product");
}
return "redirect:/applicationManage?" + MESSAGE_KEY;
}
#RequestMapping(path = "/applicationManage")
public String viewApplicationPage(Model model) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = 0;
String agency = "";
String units = "";
String jobroles = "";
if (principal != null && principal instanceof AuthenticatedUser) {
AuthenticatedUser auth = (AuthenticatedUser) principal;
userId = auth.getUserId();
agency = auth.getAgency();
if (agency.equalsIgnoreCase("slsi")) {
System.out.println("Agency of the User is " + agency);
model.addAttribute("applications", applicationServices.getApplicationsByUnit(auth.getJobUnits()));
} else {
model.addAttribute("applications", applicationServices.getApplicationsByUserId(String.valueOf(userId)));
}
}
return "applicationManage";
}
#RequestMapping(path = "/applicationView", method = RequestMethod.POST)
public String viewApplicationUpdatePage(#ModelAttribute("appId") String appId, Model model) {
model.addAttribute("application", applicationServices.getApplicationById(Integer.parseInt(appId)));
return "view";
}
#RequestMapping(value = "/download/{fileName}*", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Resource> downLoadFile(#PathVariable("fileName") String filename) {
Resource file = applicationServices.getFile(filename);
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
#RequestMapping(path = "/viewPdf/{snumber}", method = RequestMethod.POST)
public ModelAndView getPDFReport(#PathVariable("snumber") String snumber) {
File reportsDir = Paths.get(servletContext.getRealPath(reportDataLocation)).toFile();
if (!reportsDir.exists()) {
throw ProductWithSameSerialExistsException.getInstance();
}
JRDataSource dataSource = new JRBeanCollectionDataSource(Arrays.asList(applicationServices.getApplicationById(Integer.parseInt(snumber))));
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("datasource", dataSource);
parameterMap.put("JasperCustomSubReportDatasource", dataSource);
parameterMap.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportsDir));
System.out.println(dataSource);
return new ModelAndView("pdfReport", parameterMap);
}
}
My JSP IS (EDIT JSP).I want to edit some selected fields only in my form.So i creaded new JSP for edit application,
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Application</title>
<meta charset="UTF-8">
<%#include file="template/styles.jsp" %>
<script src="${pageContext.request.contextPath}/view/public/js/jquery.min.js"></script>
<script src="${pageContext.request.contextPath}/view/public/js/jquery-ui.min.js"></script>
</head>
<sec:authorize/>
<body>
<div class="container">
<!-- Start of common header -->
<div class="row headerRow1">
<div class="col-md-12">
<jsp:include page="template/banner.jsp"/>
</div>
</div>
<div class="row">
<div class="authheader">
<%#include file="template/message.jsp" %>
</div>
</div>
<div class="col-sm-12">
<div class="row">
<div class="col-lg-12">
<div class="well lead">UPDATE NOTIFICATION FORM - SLSI ENTRY NO ${app.snumber}</div>
</div>
</div>
<div id="" style="color: red">Use Google Chrome Web browser for update your Application.</div>
<div class="row">
<!-- Start of common navigation -->
<form:form name="updateapplicationForm" id="updateapplicationForm" action="updateUserApplication" commandName="app" method="post" enctype="application/x-www-form-urlencoded">
<c:if test="${edit}">
<input type="text" id="snumber" name="snumber" value="${app.snumber}"/>
</c:if>
<div class="panel panel-default">
<div class="panel-body" >
<div class="row">
<label id="aaa" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name &
Address <div class="req" > *</div></label>
<label id="bbb" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name <div class="req" > *</div></label>
<div id="">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" value="" id="registered">Registered Manufacturer in SLSI</label>
</div>
<div id="regManu">
<select id="companies">
<c:forEach items="${manu}" var="com">
<option value="${com.manufacturerName}">${com.manufacturerName}</option>
</c:forEach>
</select>
</div>
<textarea name="manufacturer" class="form-control form-control-lg"
id="manufacturer"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="4" maxlength="254"></textarea>
<input type="hidden" id="manufacture" name="manufacture" value="${app.manufacturer}"/>
<div class="help-block with-errors"></div>
</div>
<label for="exporterAddress" class="col-sm-2 col-form-label col-form-label-lg">Exporter Name &
Address <div class="req"> *</div></label>
<div class="col-sm-4">
<textarea name="exporterAddress" class="form-control form-control-lg" id="exporterAddress"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="5" maxlength="254"></textarea><br/><br/>
<input type="hidden" id="exp" name="exp" value="${app.exporterAddress}"/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<br/> <label for="importerVAT" class="col-sm-2 col-form-label col-form-label-lg">Importer VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" type="text" name="importerVAT" id="importerVAT"
aria-describedby="importerVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.importerVAT}">
<div class="help-block with-errors"></div>
</div>
<label for="declarantVAT" class="col-sm-2 col-form-label col-form-label-lg">Declarant VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" name="declarantVAT" type="text" id="declarantVAT"
aria-describedby="declarantVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.declarantVAT}">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" id="submit" class="btn btn-success pull-right">SAVE CHANGES</button>
</div>
<div class="col-sm-3" id="msg">
<% if (message.startsWith("Registration")) {
out.print("<script>alert('" + message + "');</script>");
request.getSession().setAttribute("regMessage", "");
}
%>
</div>
</div>
</form:form>
</div>
<jsp:include page="template/footer.jsp"/>
</div>
</body>
</html>
Data retrive succecfully to the edit jsp..but when i hit sava button it will get the error..I want to update application...
Please help me.
error is
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Nov 07 12:32:42 IST 2017
There was an unexpected error (type=Internal Server Error, status=500).
For input string: "updateUserApplication"
in my netbeans console show this error
java.lang.NumberFormatException: For input string: "updateUserApplication"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_121]
at java.lang.Integer.parseInt(Integer.java:580) ~[na:1.8.0_121]
at java.lang.Integer.parseInt(Integer.java:615) ~[na:1.8.0_121]
at lk.slsi.controller.ApplicationUrlMapController.addApplication(ApplicationUrlMapController.java:81) ~[classes/:na]
at sun.reflect.GeneratedMethodAccessor842.invoke(Unknown Source) ~[na:na]
From the controller code, the API endpoint /slsi_mof/EditApplication/{snumber} is getting invoked. It is because you are using relative URL in form action. Update the form action to /slsi_mof/updateUserApplication and it should work

Resources