I'm trying to update data from Spring MVC's view. I could update data using tester object but failed when trying update from Spring MVC's view. POST request from view has no problem key/value were posting to server. It updated my table data but with null value (unless for id field).
Please help and thank you.
My Table (tx_surveyrequest)
CREATE TABLE tx_surveyrequest
(
id uuid NOT NULL,
id_person uuid,
id_surveyrequeststatus uuid,
id_validationstatus uuid,
id_employee_assistantgis uuid,
formcode character varying(64),
b_north character varying(32),
b_east character varying(32),
b_south character varying(32),
b_west character varying(32),
hectarage numeric(10,2),
is_priority boolean DEFAULT false,
requestdate date,
surveyplandate date,
surveyplantime time without time zone,
requestedby character varying(32),
requestedprice numeric(14,2),
CONSTRAINT pk_tx_surveyrequest PRIMARY KEY (id)
)
My domain object (SurveyRequest)
#Entity
#Table(name = "tx_surveyrequest")
public class SurveyRequest implements Serializable {
private UUID id;
private Person person;
private String formCode;
private String borderNorth;
private String borderEast;
private String borderSouth;
private String borderWest;
private Double hectarage;
private Boolean priority;
private DateTime requestDate;
private DateTime surveyPlanDate;
private LocalTime surveyPlanTime;
private String requestedBy;
private Double requestedPrice;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id")
#Type(type="pg-uuid")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#Column(name = "hectarage")
public Double getHectarage(){
return hectarage;
}
public void setHectarage(Double hectarage){
this.hectarage = hectarage;
}
#Column(name = "formcode")
public String getFormCode() {
return formCode;
}
public void setFormCode(String formCode) {
this.formCode = formCode;
}
#Column(name="is_priority")
public Boolean getPriority() {
return priority;
}
public void setPriority(Boolean priority) {
this.priority = priority;
}
#Column(name="b_north")
public String getBorderNorth() {
return borderNorth;
}
public void setBorderNorth(String border) {
this.borderNorth = border;
}
#Column(name="b_east")
public String getBorderEast() {
return borderEast;
}
public void setBorderEast(String border) {
this.borderEast = border;
}
#Column(name="b_south")
public String getBorderSouth() {
return borderSouth;
}
public void setBorderSouth(String border) {
this.borderSouth = border;
}
#Column(name="b_west")
public String getBorderWest() {
return borderWest;
}
public void setBorderWest(String border) {
this.borderWest = border;
}
// TODO replace pattern with i18n
#Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "requestdate")
public DateTime getRequestDate() {
return requestDate;
}
public void setRequestDate(DateTime requestDate) {
this.requestDate = requestDate;
}
// TODO replace pattern with i18n
#Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "surveyplandate")
public DateTime getSurveyPlanDate() {
return surveyPlanDate;
}
public void setSurveyPlanDate(DateTime surveyPlanDate) {
this.surveyPlanDate = surveyPlanDate;
}
// TODO replace pattern with i18n
#Type(type = "org.joda.time.contrib.hibernate.PersistentLocalTimeAsTime")
#DateTimeFormat(pattern = "HH:mm")
#Column(name = "surveyplantime")
public LocalTime getSurveyPlanTime() {
return surveyPlanTime;
}
public void setSurveyPlanTime(LocalTime surveyPlanTime) {
this.surveyPlanTime = surveyPlanTime;
}
Update success using SurveyRequestUpdate
public class SurveyRequestUpdate {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:spring-data-app-context.xml");
ctx.load("classpath:datasource.xml");
ctx.refresh();
SurveyRequestService surveyRequestService = ctx.getBean(
"springJpaSurveyRequestService",SurveyRequestService.class);
UUID uid = UUID.fromString("0cd02976-1864-447b-b540-39d6e7ee3703");
SurveyRequest request = surveyRequestService.findById(uid);
System.out.println("Find by ID");
System.out.println(request);
request.setSurveyPlanDate (new DateTime(2014,7,1,0,0));
request.setSurveyPlanTime (new LocalTime(22,0));
surveyRequestService.save(request);
System.out.println(request);
}
Update Form View
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<spring:message code="l_surveyrequest_list" var="labelSurveyRequestList" />
<spring:message code="l_surveyrequest_title" var="labelSurveyRequestTitle" />
<spring:message code="l_surveyrequest_code" var="labelSurveyRequestCode" />
<spring:message code="l_surveyrequest_requestdate" var="labelSurveyRequestRequestDate" />
<spring:message code="l_surveyrequest_surveydate" var="labelSurveyRequestSurveyDate" />
<spring:message code="l_surveyrequest_surveytime" var="labelSurveyRequestSurveyTime" />
<spring:message code="l_surveyrequest_priority" var="labelSurveyRequestPriority" />
<spring:message code="l_surveyrequest_complete" var="labelSurveyRequestComplete" />
<spring:message code="l_surveyrequest_hectarage" var="labelSurveyRequestHectarage" />
<spring:message code="l_surveyrequest_north" var="labelSurveyRequestNorth" />
<spring:message code="l_surveyrequest_east" var="labelSurveyRequestEast" />
<spring:message code="l_surveyrequest_south" var="labelSurveyRequestSouth" />
<spring:message code="l_surveyrequest_west" var="labelSurveyRequestWest" />
<spring:message code="form_new" var="formNew" />
<spring:message code="form_edit" var="formEdit" />
<spring:message code="btn_save" var="buttonSave" />
<spring:message code="btn_cancel" var="buttonCancel" />
<spring:message code="long_date_format_pattern" var="formatDate" />
<spring:message code="time_format_pattern" var="formatDateTime" />
<spring:message code="short_time_format_pattern" var="formatShortTime" />
<spring:url value="/surveyrequest" var="showSurveyRequestUrl" />
<spring:eval expression="surveyRequest.id == null ? formNew:formEdit" var="formTitle"/>
<div class="row">
<div class="col-md-12">
<h1>${formTitle} ${labelSurveyRequestTitle}</h1>
</div>
</div>
<!-- /top action bar -->
<div class="row">
<div class="col-md-12">
<c:if test="${not empty surveyRequest}">
<form:form class="form-horizontal"
modelAttribute="surveyRequest" commandName="surveyRequest" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-primary">${buttonSave}</button>
<button type="reset" class="btn btn-primary">${buttonCancel}</button>
</div>
</div>
<c:if test="${not empty message}">
<div id="message" class="${message.type}">${message.message}</div>
</c:if>
<div class="form-group">
<label class="col-md-3 control-label">${labelSurveyRequestCode}</label>
<div class="col-md-3">
<form:input type="text" class="form-control" path="formCode" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">${labelSurveyRequestRequestDate}</label>
<div class='col-md-3 input-group date datepicker'>
<form:input type='text' class="form-control" path="requestDate" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">${labelSurveyRequestSurveyDate}</label>
<div class='col-md-3 input-group date datepicker'>
<form:input type='text' class="form-control" path="surveyPlanDate" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<form:label class="col-md-3 control-label"
path="surveyPlanTime">${labelSurveyRequestSurveyTime}</form:label>
<div class='col-md-3 input-group date timepicker'>
<form:input type='text' class="form-control" path="surveyPlanTime" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">${labelSurveyRequestHectarage}</label>
<div class="col-md-3">
<form:input type="text" class="form-control" path="hectarage" />
</div>
</div>
<div class="form-group">
<p class="col-md-3"></p>
<div class="col-md-9">
<c:choose>
<c:when test="${surveyRequest.priority == true}">
${labelSurveyRequestPriority}
</c:when>
</c:choose>
</div>
</div>
<div class="form-group">
<p class="col-md-3"></p>
<div class="col-md-9">
<table class="table">
<thead>
<tr>
<th>${labelSurveyRequestNorth}</th>
<th>${labelSurveyRequestEast}</th>
<th>${labelSurveyRequestSouth}</th>
<th>${labelSurveyRequestWest}</th>
</tr>
</thead>
<tbody>
<tr>
<td>${surveyRequest.borderNorth}</td>
<td>${surveyRequest.borderEast}</td>
<td>${surveyRequest.borderSouth}</td>
<td>${surveyRequest.borderWest}</td>
</tr>
</tbody>
</table>
</div>
</div>
</form:form>
</c:if>
</div>
</div>
<script type="text/javascript">
$(function () {
$('.datepicker').datetimepicker({
pickTime: false,
language: 'id',
});
$('.timepicker').datetimepicker({
pickDate: false,
minuteStepping:15,
useSeconds: false,
language: 'id'
});
});
</script>
</div>
My Controller
#RequestMapping("/surveyrequest")
#Controller
public class SurveyRequestController {
private static final int PAGE_SIZE = 10;
private static final Logger logger = LoggerFactory
.getLogger(SurveyRequestController.class);
#Autowired
MessageSource messageSource;
#Autowired
private SurveyRequestService surveyRequestService;
// Others code omitted
#RequestMapping(value="/{id}", method = RequestMethod.GET)
public String show(#PathVariable("id") UUID id, Model model) {
SurveyRequest request = surveyRequestService.findById(id);
model.addAttribute("surveyRequest", request);
return "surveyrequest/show";
}
/*
* Edit a survey request
*/
#RequestMapping(value="/{id}", params="form", method = RequestMethod.GET)
public String updateForm(#PathVariable("id") UUID id, Model model) {
SurveyRequest request = surveyRequestService.findById(id);
model.addAttribute("surveyRequest", request);
return "surveyrequest/edit";
}
/*
* Update a survey request
*/
#RequestMapping(value = "/{id}", params = "form", method = RequestMethod.POST)
public String update(SurveyRequest surveyRequest, BindingResult bindingResult, Model uiModel,
HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("message", new Message("error", messageSource.getMessage("surveyrequest_save_fail", new Object[]{}, locale)));
uiModel.addAttribute("surveyRequest", surveyRequest);
return "surveyrequest/update";
}
uiModel.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("surveyrequest_save_success", new Object[]{}, locale)));
logger.info("Before paste: " + surveyRequest);
surveyRequestService.save(surveyRequest);
return "redirect:/surveyrequest/" + UrlUtil.encodeUrlPathSegment(surveyRequest.getId().toString(), httpServletRequest);
}
Updated:
I could resolve the problem with removing enctype="multipart/form-data" at edit.jspx. But it raised another issue, how if I'm going to upload file?
Add #ModelAttribute annotation to your model object parameter in the controller method that you're calling, so that Spring knows that's the object that you want to bind the form data to.
/*
* Update a survey request
*/
#RequestMapping(value = "/{id}", params = "form", method = RequestMethod.POST)
public String update(#ModelAttribute("surveyRequest") SurveyRequest surveyRequest,
BindingResult bindingResult, Model uiModel,
HttpServletRequest httpServletRequest,
RedirectAttributes redirectAttributes, Locale locale) {
[...]
}
Related
Hello comunity I need your help with a problem in my proyect, i need to add details in the database at the same time, I have been researching how to do, I found the solution is using a iterator or a bucle for, When I use the bucle obvious I need to use arrays, I did it, But I have a object, i did the conversion (cast), but when i add the details at the web i can't because appears this error
Basically the error is the program can't cast a String to Object(Class)
There was an unexpected error (type=Internal Server Error, status=500).
class java.lang.String cannot be cast to class com.app.inventory.model.Product (java.lang.String is in module java.base of loader 'bootstrap'; com.app.inventory.model.Product is in unnamed module of loader
org.springframework.boot.devtools.restart.classloader.RestartClassLoader #6817e14)
java.lang.ClassCastException: class java.lang.String cannot be cast to class com.app.inventory.model.Product (java.lang.String is in module java.base of loader 'bootstrap'; com.app.inventory.model.Product is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader #6817e14)
Model
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id_orden_compra;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date Fecha;
#Column(name="SubTotal",length=40)
private int SubTot;
#Column(name="Total",length=40)
private int Total;
#ManyToOne
#JoinColumn(name="id_Supplier_fk", referencedColumnName = "id_Proveedor")
private Supplier id_Supplier_fk;
#OneToMany(mappedBy = "id_PurchaseOrder_fk", cascade = CascadeType.ALL)
private List<Detalle_OrderCompra> detalles = new ArrayList<>();
public long getId_orden_compra() {
return id_orden_compra;
}
public void setId_orden_compra(Long id_orden_compra) {
this.id_orden_compra = id_orden_compra;
}
public Date getFecha() {
return Fecha;
}
public void setFecha(Date fecha) {
Fecha = fecha;
}
public Supplier getId_Supplier_fk() {
return id_Supplier_fk;
}
public int getSubTot() {
return SubTot;
}
public void setSubTot(int subTot) {
SubTot = subTot;
}
public int getTotal() {
return Total;
}
public void setTotal(int total) {
Total = total;
}
public void setId_Supplier_fk(Supplier id_Supplier_fk) {
this.id_Supplier_fk = id_Supplier_fk;
}
public Purchaseorder(Long id_orden_compra, Date fecha, int subTot, int total, Supplier id_Supplier_fk) {
super();
this.id_orden_compra = id_orden_compra;
Fecha = fecha;
SubTot = subTot;
Total = total;
this.id_Supplier_fk = id_Supplier_fk;
}
public Purchaseorder(Date fecha, int subTot, int total, Supplier id_Supplier_fk) {
super();
Fecha = fecha;
SubTot = subTot;
Total = total;
this.id_Supplier_fk = id_Supplier_fk;
}
public Purchaseorder(Date fecha) {
super();
Fecha = fecha;
}
public Purchaseorder() {
super();
}
//With this constructor I add the details in the database
public void añadirDetalles(int can, Product id_prod_fk){
this.detalles.add(new Detalle_OrderCompra(can, id_prod_fk ,this));
}
public List<Detalle_OrderCompra> getDetalles() {
return detalles;
}
public void setDetalles(List<Detalle_OrderCompra> detalles) {
this.detalles = detalles;
}
public void SetDetalle(long id_Detalle_OrderCompra,int can, Product id_prod_fk) {
this.detalles.add(new Detalle_OrderCompra(id_Detalle_OrderCompra,can, id_prod_fk, this));
}
}
Model
#Entity
#Table(name = "Detalle_OrdenCompra")
public class Detalle_OrderCompra implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id_Detalle_OrderCompra;
#Column(name="Cantidad",length=40)
private int Can;
#ManyToOne
#JoinColumn(name="id_prod_fk", referencedColumnName = "id_prod")
private Product id_prod_fk;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name="id_PurchaseOrder_fk", referencedColumnName = "id_orden_compra")
private Purchaseorder id_PurchaseOrder_fk;
public long getId_Detalle_OrderCompra() {
return id_Detalle_OrderCompra;
}
public void setId_Detalle_OrderCompra(long id_Detalle_OrderCompra) {
this.id_Detalle_OrderCompra = id_Detalle_OrderCompra;
}
public int getCan() {
return Can;
}
public void setCan(int can) {
Can = can;
}
public Product getId_prod_fk() {
return id_prod_fk;
}
public void setId_prod_fk(Product id_prod_fk) {
this.id_prod_fk = id_prod_fk;
}
public Purchaseorder getId_PurchaseOrder_fk() {
return id_PurchaseOrder_fk;
}
public void setId_PurchaseOrder_fk(Purchaseorder id_PurchaseOrder_fk) {
this.id_PurchaseOrder_fk = id_PurchaseOrder_fk;
}
public Detalle_OrderCompra(long id_Detalle_OrderCompra, int can, Product id_prod_fk,
Purchaseorder id_PurchaseOrder_fk) {
super();
this.id_Detalle_OrderCompra = id_Detalle_OrderCompra;
Can = can;
this.id_prod_fk = id_prod_fk;
this.id_PurchaseOrder_fk = id_PurchaseOrder_fk;
}
public Detalle_OrderCompra(int can, Product id_prod_fk, Purchaseorder id_PurchaseOrder_fk) {
super();
Can = can;
this.id_prod_fk = id_prod_fk;
this.id_PurchaseOrder_fk = id_PurchaseOrder_fk;
}
public Detalle_OrderCompra() {
super();
}
}
I'm not Using the service because is not nessesary
Controller
#Controller
public class PurchaseorderController {
#Autowired
PurchaseorderDao purorderdao;
#Autowired
PurchaseorderRepository purorrepo;
#Autowired
SupplierDao supdao;
#Autowired
ProductDao prodao;
#Autowired
Detalle_OrderCompraRepository detOrrepo;
#RequestMapping({ "/PurchaseOrderWEB", "/" })
public String ListUser(Model modelo) {
modelo.addAttribute("Purchase", purorderdao.EncontrarPurchase());
List<Supplier> lstSupplier = supdao.EncontrarSupplier();
modelo.addAttribute("Supplier", lstSupplier);
List<Product> lstProduct = prodao.EncontrarProduct();
modelo.addAttribute("Product", lstProduct);
List<Detalle_OrderCompra> lstdetalle = detOrrepo.findAll();
modelo.addAttribute("Detalle_OrdenCompra", lstdetalle);
return "PurchaseOrderWEB";
}
#PostMapping({ "/Purchasecrear" })
public String createDet(Purchaseorder purchaseorder, HttpServletRequest request) {
String[] DetallesIDs = request.getParameterValues("detallesIDs");
String[] DetallesCan = request.getParameterValues("detallesCan");
Object[] DetallesProd = request.getParameterValues("detallesProd");
//With this bucle for i add the Details
for (int i = 0; i < DetallesCan.length; i++) {
if (DetallesIDs != null && DetallesIDs.length > 0) {
purchaseorder.SetDetalle(Long.valueOf(DetallesIDs[i]), Integer.valueOf(DetallesCan[i]),
(Product) (DetallesProd[i]));
} else {
purchaseorder.añadirDetalles(Integer.parseInt(DetallesCan[i]),
(Product) (DetallesProd[i]));
}
}
purorrepo.save(purchaseorder);
return "redirect:/";
}
}
HTML
<head>
<meta charset="utf-8">
<title>Crud Purchase Order</title>
<link rel="stylesheet" th:href="#{/css/bootstrap.min.css}" />
<link rel="stylesheet" th:href="#{/css/StylesUS.css}" />
<script src="https://code.jquery.com/jquery-3.6.1.js"
integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#4.4.1/dist/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<script type="text/javascript" src="../static/js/UpdateProduct.js"
th:src="#{/js/UpdateProduct.js}"></script>
</head>
<body>
<a><button class="ov-btn-grow-box"
onclick="document.getElementById('id01').style.display='block'">Crear</button></a>
<a class="ov-btn-slide-close" th:href="#{/}">Regresar</a>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'"
class="close" title="Close Modal">×</span>
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 container justify-content-center card">
<center>
<h1>Registro de Ordenes de compra</h1>
</center>
<div class="ard-body">
<form th:action="#{/Purchasecrear}" method="post">
<div class="form-row row">
<div class="col-md-6">
<div class="form-group">
<label>Fecha:</label><br> <input type="date" name="Fecha"><br>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Subtotal:</label><br> <input type="text"
placeholder="Ingrese nombre producto" name="Subtotal"><br>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Total:</label><br> <input type="number"
placeholder="Ingrese precio compra" name="Total"><br>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Proveedores:</label> <select class="form-select"
name="id_Supplier_fk">
<th:block th:each="sup : ${Supplier}">
<option th:text="${sup.nom}" th:value="${sup.id_Proveedor}"></option>
</th:block>
</select>
</div>
</div>
<!-- Agregamos Los Detaless -->
<div class="form-group row">
<label class="col-form-label col-sm-4">Detalles #1 : </label>
<h4>Cantidad</h4>
<div class="col-sm-4">
<input type="text" name="detallesCan" class="form-control"
placeholder="Nombre" required>
</div>
<h4>Producto</h4>
<select class="form-select" name="detallesProd" id="id_prod_fk">
<th:block th:each="prod : ${Product}">
<option th:text="${prod.nom}" th:value="${prod.id_prod}"></option>
</th:block>
</select>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-4">Detalles #2 : </label>
<h4>Cantidad</h4>
<div class="col-sm-4">
<input type="text" name="detallesCan" class="form-control"
placeholder="Nombre" required>
</div>
<h4>Producto</h4>
<select class="form-select" name="detallesProd" id="id_prod_fk">
<th:block th:each="prod : ${Product}">
<option th:text="${prod.nom}" th:value="${prod.id_prod}"></option>
</th:block>
</select>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-4">Detalles #3 : </label>
<h4>Cantidad</h4>
<div class="col-sm-4">
<input type="text" name="detallesCan" class="form-control"
placeholder="Nombre" required>
</div>
<h4>Producto</h4>
<select class="form-select" name="detallesProd" id="id_prod_fk">
<th:block th:each="prod : ${Product}">
<option th:text="${prod.nom}" th:value="${prod.id_prod}"></option>
</th:block>
</select>
</div>
<div class="container">
<button type="submit" class="ov-btn-slide-left">Guardar</button>
<br> <br>
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="o-btn-slide-left">Cancelar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I'm using Spring Tool Suite
I just need to fill two tables and add many details at the same time
I fill the form, but It doesn't add the details, i don't know what happend, please if you don't understnad please contact me
Here is my form
<form th:action="#{/pages/org/create}" th:object="${org}" method="post" id="createOrgForm">
<div class="row">
<div class="form-group col-sm-12">
<label for="name">Name</label> <input class="form-control" id="name" type="text" th:field="*{name}" />
</div>
</div>
<div class="row">
<div class="form-group col-sm-12">
<label for="uuid">Uuid</label> <input class="form-control" id="uuid" type="text" th:field="*{uuid}" />
</div>
</div>
<div class="row">
<div class="form-group col-sm-12">
<label for="expiryDate">Expiry Date</label>
<input class="form-control" id="expiryDate" type="date" name="expiryDate" th:value="${#temporals.format(org.expiryDate, 'dd/MMM/yyyy HH:mm', 'en')}"/>/>
</div>
</div>
</form>
The object has name and uuid which are strings
It also has an expiryDate which is a zonedDateTime
I want to return expiryDate as a zoneddatetime but I can't find any examples of this
Any one Know how to do this?
If anymore details are needed let me know
I have this error
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='org'. Error count: 1
because org.expiryDate is a string and its expecting a zoneddatetime
public class OrganizationDto extends TemporallyScopedEntityFlatDto {
private static final long serialVersionUID = -2191341305487098272L;
public static OrganizationDto fromEntity(final Organization o) {
if (o == null) {
return null;
}
final OrganizationDto dto = new OrganizationDto();
DtoUtil.copyVersioned(o, dto);
DtoUtil.copyTemporallyScoped(o, dto);
dto.setName(o.getName());
dto.setUuid(o.getUuid());
return dto;
}
#ApiModelProperty(value = "The display name of this organization.")
private String name;
#ApiModelProperty(value = "The unique identifier of this organization.")
private String uuid;
private ZonedDateTime expiryDate;
public String getName() {
return name;
}
public String getUuid() {
return uuid;
}
public void setName(final String name) {
this.name = name;
}
public void setUuid(final String uuid) {
this.uuid = uuid;
}
}
Hi i want to add my photo to mysql database but it doesn't work, I have BLOB in workbench but when I open value in editor I see only name of image and binary values, I don't have look at the picture and size of BLOB do not agree with size of image. Text entites correctly save to rows.
MODEL:
#Entity
#Table(name = "skis")
public class Skis extends BaseEntity {
#Column(name = "company", length = 20)
private String company;
#Column(name = "model", length = 20)
private String model;
#Column(name = "description", length = 200)
private String description;
#Column(name = "photo", columnDefinition = "MEDIUMBLOB")
private byte[] photo;
public Skis(String company, String model, String description, byte[] photo) {
this.company = company;
this.model = model;
this.description = description;
this.photo = photo;
}
public Skis() {
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
}
Controller:
#Controller
public class SkisController {
#Autowired
private SkisDAO skisDAO;
#RequestMapping(value = "/ski/save", method = RequestMethod.POST)
public String postCreateSki(#ModelAttribute Skis skis){
skisDAO.save(skis);
return "redirect:/skis";
}
#RequestMapping(value = "/ski-create", method = RequestMethod.GET)
public String getCreateSkisForm(Model model) {
model.addAttribute("skis", new Skis());
return "add-skis";
}
}
JSP:
<div class="container">
<div class="row">
<form:form commandName="skis" action="${createSkiURL}" method="post" role="form" class="form-horizontal">
<form:hidden path="id" />
<div class="form-group">
<label class="control-label col-sm-2" for="company">company:</label>
<div class="col-sm-6">
<form:input path="company" type="text" id="company" class="form-control" placeholder="Enter company" autofocus="autofocus" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="model">model:</label>
<div class="col-sm-6">
<form:input path="model" type="text" id="model" class="form-control" placeholder="Enter model" autofocus="autofocus" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="description">description:</label>
<div class="col-sm-6">
<form:input path="description" type="text" id="description" class="form-control" placeholder="Enter description" autofocus="autofocus" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="photo">photo:</label>
<form:input path="photo" type="file" id="photo" />
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-primary">Zapisz</button>
</div>
</div>
</form:form>
</div>
</div>
DAO:
#Repository
public interface SkisDAO extends JpaRepository<Skis, Long> {
}
And another question:
How Can I display image at another jsp? I know how display text, but don't know how to display photo from database
When trying to submit my form to create a new auction this error appears in the browser:
Whitelabel Error Page:
This application has no explicit mapping for /error, so you are seeing
this as a fallback.
Thu Mar 30 21:00:15 BST 2017
There was an unexpected error (type=Bad Request, status=400)
Validation failed for object='auctionItem'. Error count: 2
I can't seem to find any specific errors within my log, so I am having trouble finding the two validation errors show on the error page. I am pretty lost at this point. Hopefully someone can help me out, its preventing me from making progress at the moment.
JSP File:
<body id="product" class="product">
<header>
<%#include file="../jsp/Header.jsp" %>
</header>
<div>
<div class="container">
<div class ="row">
<div class="center_column">
<h2 style=" ">Create New Listing</h2>
<mvc:form class="form-inline" action="sell" method="post" modelAttribute="newAuction" id="addNewAuc">
<div class="form-inline" cssClass="TitleBlock">
<label class="control-label">Title</label>
<div>
<mvc:input path="aTitle" type="text" required="true" cssClass="Title" class="form-control" placeholder="Please enter title of item" maxlength="55" minlength="40"/>
</div>
</div>
<div class="form-group ">
<label class="control-label">Item Condition</label>
<div style="padding-top: 4px;">
<mvc:select path="aCondition">
<mvc:option value="New">New</mvc:option>
<mvc:option value="Used">Used</mvc:option>
</mvc:select>
</div>
</div>
<div class="form-group ">
<label class="control-label" style = "padding-left: 15px;">Can the item be returned?</label>
<div style="padding-top: 4px; padding-left: 15px;">
<mvc:select path="aReturns">
<mvc:option value="You can return">Yes</mvc:option>
<mvc:option value="Seller does not offer returns">No</mvc:option>
</mvc:select>
</div>
</div>
<div class="form-inline">
<label class="control-label">Description</label>
<div>
<mvc:textarea path="aDescription" required="true" cssClass="Desc" class="form-control" rows="3" name="Description" placeholder="Item description"/>
</div>
</div>
<div class="form-inline">
<label class="control-label">Category</label>
<div style="padding-top: 4px;">
<mvc:select path="categories">
<mvc:option value="category1">Electronics</mvc:option>
<mvc:option value="category2">Fashion</mvc:option>
<mvc:option value="category3">Home & Gardens</mvc:option>
<mvc:option value="category4">Toys & Games</mvc:option>
<mvc:option value="category5">Sports & Leisure</mvc:option>
</mvc:select>
</div>
</div>
<div class="form-inline">
<label class="control-label ">Minimum Price</label>
<div style="padding-top: 4px;">
<mvc:input path="aBottomPrice" type="number" step="any" required="true" class="form-control" placeholder="?"/>
</div>
</div>
<div class="form-inline">
<label class="control-label ">Starting Price</label>
<div style="padding-top: 4px;">
<mvc:input path="aTopPrice" type="number" step="any" required="true" class="form-control" placeholder="?"/>
</div>
</div>
<div class="form-inline">
<label class="control-label">End of listing</label>
<div style="padding-top: 4px;">
<mvc:input path="aEnd" type="text" id="datetimepicker" required="true" class="form-control" placeholder="YYYY-MM-DD"/>
</div>
</div>
</mvc:form>
<div class="form-inline">
<div style="padding-top: 10px;">
<button type="submit" name="submit" class="btn btn-success" form="addNewAuc">Next</button>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
AuctionItem Class
#Entity
#Table(name = "auction_items")
public class AuctionItem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idauction;
#Column(name = "auctionTitle")
private String aTitle;
#Column(name = "auctionDescription")
private String aDescription;
#Column(name = "auctionStatus")
private String aStatus;
#Column(name = "auctionStart")
private Date aStart;
#Column(name = "auctionEnd")
private Date aEnd;
private String endTimeAsString;
#Column(name = "auctionCondition")
private String aCondition;
#Column(name = "auctionTopPrice")
private double aTopPrice;
#Column(name = "auctionBottomPrice")
private double aBottomPrice;
private long auctionDuration;
private String aReturns;
#ManyToOne
#JoinColumn(name = "owner")
private User owner;
#ManyToOne
#JoinColumn(name = "cId")
private Category categories;
public long getAuctionDuration() {
return auctionDuration;
}
public void setAuctionDuration(long auctionDuration) {
this.auctionDuration = auctionDuration;
}
public int getaID() {
return idauction;
}
public void setaID(int idauction) {
this.idauction = idauction;
}
public String getaTitle() {
return aTitle;
}
public void setaTitle(String aTitle) {
this.aTitle = aTitle;
}
public String getaDescription() {
return aDescription;
}
public void setaDescription(String aDescription) {
this.aDescription = aDescription;
}
public String getaStatus() {
return aStatus;
}
public void setaStatus(String aStatus) {
this.aStatus = aStatus;
}
public Date getaStart() {
return aStart;
}
public void setaStart(Date aStart) {
this.aStart = aStart;
}
public Date getaEnd() {
return aEnd;
}
public void setaEnd(Date aEnd) {
this.aEnd = aEnd;
}
public String getaCondition() {
return aCondition;
}
public void setaCondition(String aCondition) {
this.aCondition = aCondition;
}
public double getaTopPrice() {
return aTopPrice;
}
public void setaTopPrice(double aTopPrice) {
this.aTopPrice = aTopPrice;
}
public double getaBottomPrice() {
return aBottomPrice;
}
public void setaBottomPrice(double aBottomPrice) {
this.aBottomPrice = aBottomPrice;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public String getaReturns() {
return aReturns;
}
public void setaReturns(String aReturns) {
this.aReturns = aReturns;
}
public Category getCategories() {
return categories;
}
public void setCategories(Category categories) {
this.categories = categories;
}
public String getEndTimeAsString() {
return endTimeAsString;
}
public void setEndTimeAsString(String EndTimeAsString) {
this.endTimeAsString = EndTimeAsString;
}
}
Maybe you missed " BindingResult " in Controller.
Example:
import org.springframework.validation.BindingResult;
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(
#ModelAttribute("userlogin") #Valid LoginProfile userlogin,
BindingResult userloginResult)
When I load page for create a new article, all categories is displayed in select box.
When I complete form for a new article and click on the submit button, it saves all data from form to the database but categories isn't joined with an article.
Do you understand me what I think? What could be an issue?
ArticleController.class
#Controller
public class ArticleController {
#Autowired
ArticleService articleService;
#Autowired
CategoryService categoryService;
#Autowired
UserService userService;
#ModelAttribute("article")
public Article construct() {
return new Article();
}
/**
* Method displays page with all articles, categories and users
* (articles.jsp)
* */
#RequestMapping("/admin/articles")
public String articles(Model model) {
model.addAttribute("articles", articleService.findAll());
model.addAttribute("categories", categoryService.findAll());
model.addAttribute("users", userService.findAll());
return "articles";
}
/**
* Method for display article's detail (article-detail.jsp)
* */
#RequestMapping("/admin/articles/{id}")
public String userDetail(Model model, #PathVariable Integer id) {
model.addAttribute("articles", articleService.findAll());
model.addAttribute("article", articleService.findById(id));
return "article-detail";
}
/**
* Method for display article's add page (article-add.jsp)
* */
#RequestMapping("/admin/articles/new")
public String articleAdd(Model model) {
model.addAttribute("articles", articleService.findAll());
model.addAttribute("categories", categoryService.findAll());
model.addAttribute("users", userService.findAll());
return "article-add";
}
/**
* Method for save article
* */
#RequestMapping(value = "/admin/articles/new", method = RequestMethod.POST)
public String saveArticle(#ModelAttribute("article") Article article,
BindingResult result) {
Date publishDate = new Date();
article.setPublishDate(publishDate);
articleService.save(article);
return "redirect:/admin/articles.html?success=true";
}
/**
* Binder for required date format
* */
#InitBinder
public void initBinder(WebDataBinder webDataBinder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
dateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class, "publishDate",
new CustomDateEditor(dateFormat, false));
}}
article-add.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# include file="../layouts/taglibs.jsp"%>
<form:form commandName="article" cssClass="form-horizontal">
<div class="form-group">
<form:hidden path="id" class="form-control input-sm" />
</div>
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Titulek</label>
<div class="col-sm-10">
<form:input path="title" cssClass="form-control" />
</div>
</div>
<div class="form-group">
<label for="content" class="col-sm-2 control-label">Text</label>
<div class="col-sm-10">
<form:textarea path="content" cssClass="form-control" rows="10" />
</div>
</div>
<div class="form-group">
<label for="categories" class="col-sm-2 control-label">Kategorie</label>
<div class="col-sm-10">
<form:select path="categories" items="${categories}" itemLabel="name" itemValue="id" multiple="true" cssClass="form-control" />
</div>
</div>
<div class="form-group">
<label for="user" class="col-sm-2 control-label">Uživatel</label>
<div class="col-sm-10">
<form:select path="user.id" items="${users}" value="${user.id}" itemLabel="name" itemValue="id" cssClass="form-control" />
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<input type="submit" value="Uložit" class="btn btn-primary">
</div>
</div>
Category.class
#Entity
public class Category {
#Id
#GeneratedValue
private Integer id;
#Size(min=3, max=20, message="Název musí obsahovat 3-20 znaků!")
private String name;
#ManyToMany(mappedBy = "categories", cascade = CascadeType.REMOVE)
private List<Article> articles;
/**
* Getters and setters
* */
}
-- SOLVED --
I solved this problem by adding:
#InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Category.class, "categories", new PropertyEditorSupport() {
#Override
public void setAsText(String text) {
Category c = categoryService.findById(Integer.parseInt(text));
setValue(c);
}
});
}