I am developing an application for managing clients an its machines.
I have created all necessary tables, schema, controllers etc.
Client entity has List and Machine has Client relation (bidiretional, non-optional).
The problem I have is related to adding brand new machine to existing Client (providing this one already exists).
So here is some short snip of code:
#Controller
public class MachineController {
...
#GetMapping("/machines/add/{clientId}")
public String addMachine(#PathVariable("clientId") int clientId, Model model) throws ClientNotFoundException {
model.addAttribute("machineTypes", MachineType.values());
model.addAttribute("machine", new Machine());
model.addAttribute("client", clientService.find(clientId));
return "machines/form";
}
}
#PostMapping("/machines/save")
public String saveMachine(#ModelAttribute #Valid Machine machine, BindingResult bindingResult, Model model)
throws ClientNotFoundException {
model.addAttribute("machineTypes", MachineType.values());
int clientId = machine.getClient().getId();
LOG.debug("ClientId:{}", clientId);
// Client object is not filled here ! clientId is 0 (new client).
}
The problem is with save function - I don't know how to pass exisitng Client object for Machine object, which is sent by HTTP POST.
My controller complains that client is not send and BindingResult is throwing error:
Field error in object 'machine' on field 'client.address.city:
rejected value [null]; Field error in object 'machine' on field
'client.address.zipCode: rejected value [null]; Field error in object
'machine' on field 'client.name': rejected value [null];
I am loooking forward to any help.
HTML form presented below:
<form class="form-horizontal" th:action="#{/machines/save}" th:object="${machine}" method="post" id="machineForm">
<input type="hidden" th:field="*{id}"/>
<!-- Panel for machine -->
<div th:class="${#fields.hasErrors('machineType')}? 'form-group has-error has-feedback' : 'form-group'">
<label class="control-label col-sm-4" for="manufacturer">Rodzaj:*</label>
<div class="col-sm-8">
<select th:field="${machine.machineType}" class="form-control" id="machineTypeSelect">
<option value="" disabled="disabled" selected="selected">Wybierz rodzaj</option>
<option th:each="type: ${machineTypes}" th:value="${type.name()}" th:text="${type}" th:attr="data-has-car=${type.hasCar()}"></option>
</select>
<div class="help-block" th:if="${#fields.hasErrors('machineType')}"
th:errors="*{machineType}"></div>
</div>
</div>
<div th:class="${#fields.hasErrors('manufacturer')}? 'form-group has-error has-feedback' : 'form-group'">
<label class="control-label col-sm-4" for="manufacturer">Producent:*</label>
<div class="col-sm-8">
<input type="text"
class="form-control"
id="manufacturer"
placeholder="Podaj producenta"
th:field="*{manufacturer}" />
<div class="help-block" th:if="${#fields.hasErrors('manufacturer')}"
th:errors="*{manufacturer}"></div>
</div>
</div>
<div th:class="${#fields.hasErrors('model')}? 'form-group has-error has-feedback' : 'form-group'">
<label class="control-label col-sm-4" for="model">Model:</label>
<div class="col-sm-8">
<input type="text"
class="form-control"
id="model"
placeholder="Podaj model"
th:field="*{model}"/>
<div class="help-block" th:if="${#fields.hasErrors('model')}"
th:errors="*{model}"></div>
</div>
</div>
<div th:class="${#fields.hasErrors('productionYear')}? 'form-group has-error has-feedback' : 'form-group'">
<label class="control-label col-sm-4" for="productionYear">Rok produkcji:*</label>
<div class="col-sm-8">
<input type="number"
class="form-control"
id="productionYear"
placeholder="Podaj rok produkcji"
th:field="*{productionYear}"/>
<div class="help-block" th:if="${#fields.hasErrors('productionYear')}"
th:errors="*{productionYear}"></div>
</div>
</div>
<div th:class="${#fields.hasErrors('factoryNo')}? 'form-group has-error has-feedback' : 'form-group'">
<label class="control-label col-sm-4" for="factoryNo">Numer fabryczny:</label>
<div class="col-sm-8">
<input type="number"
class="form-control"
id="factoryNo"
placeholder="Podaj numer fabryczny"
th:field="*{factoryNo}"/>
<div class="help-block" th:if="${#fields.hasErrors('factoryNo')}"
th:errors="*{factoryNo}"></div>
</div>
</div>
<div th:class="${#fields.hasErrors('maxLoad')}? 'form-group has-error has-feedback' : 'form-group'">
<label class="control-label col-sm-4" for="maxLoad">Max udżwig:</label>
<div class="col-sm-8">
<div class="input-group">
<input type="number"
class="form-control"
id="maxLoad"
placeholder="Max. udźwig"
aria-describedby="measure"
th:field="*{maxLoad}"/>
<span class="input-group-addon" id="measure">kg</span>
</div>
<div class="help-block" th:if="${#fields.hasErrors('maxLoad')}"
th:errors="*{maxLoad}"></div>
</div>
</div>
<div th:object="${machine.client}">
<div th:class="${#fields.hasErrors('id')}? 'form-group has-error has-feedback' : 'form-group'">
<label class="control-label col-sm-4" for="clientId">Wybrany klient:</label>
<div class="col-sm-8">
<span class="form-control-static" id="selectedClient">Nie wybrano! Wyszukaj po prawej</span>
<input type="hidden" th:field="${machine.client.id}" id="clientId" />
<div class="help-block" th:if="${#fields.hasErrors('id')}"
th:errors="${machine.client.id}"></div>
</div>
</div>
</div>
<div id="machineCar" th:object="${machine.car}">
<div th:class="${#fields.hasErrors('make')}? 'form-group has-error has-feedback' : 'form-group'">
<label class="control-label col-sm-4" for="carMake">Marka pojazdu:*</label>
<div class="col-sm-8">
<input type="text"
class="form-control"
id="carMake"
placeholder="Podaj markę pojazdu"
th:field="*{make}"/>
<div class="help-block" th:if="${#fields.hasErrors('make')}"
th:errors="*{make}"></div>
</div>
</div>
<div th:class="${#fields.hasErrors('vin')}? 'form-group has-error has-feedback' : 'form-group'">
<label class="control-label col-sm-4" for="factoryNo">VIN:</label>
<div class="col-sm-8">
<input type="number"
class="form-control"
id="vin"
placeholder="Podaj numer VIN"
th:field="*{vin}"/>
<div class="help-block" th:if="${#fields.hasErrors('vin')}"
th:errors="*{vin}"></div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<button type="submit" class="btn btn-primary">Zapisz dane</button>
</div>
</div>
</form>
try to add
<input type="hidden" name="client.id" value="${client.id}" />
in the form in HTML, those client object with id value will be created and then leave the rest to the repository, it just need id to associate the record.
I resolved my problem. Not sure if it's right solution, but works.
So, simply in Machine entity:
public class Machine {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MACHINE_SEQUENCE")
private int id;
// ...
#ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE} )
#JoinColumn(name = "client_id", nullable = false)
#Valid // REMOVED
private Client client;
I have removed #Valid annotation on top of Client field and therefore Spring MVC is not validating Thymeleaf form anymore.
Another solution is to include hidden inputs with client details (name, company and child address object) so thymeleaf can transfer complete Object and BindingResult won't complain ...
Related
Hello i have problem with update object, i dont know how always aftre update data i have message: Request method 'GET' not supported. But date after refresh object is update.
Controller with GET and POST method to update object
#Controller
#RequestMapping("/packet")
public class PacketController {
#GetMapping("/modify/{id}")
public String modifyPacketGet(Model model, #PathVariable Long id)
{
model.addAttribute("channels", channelService.getAllChannels());
model.addAttribute("packet", packetService.getById(id));
return "packet/modify";
}
#PostMapping("/modify")
public String modifyPacketPost(Model model, #ModelAttribute PacketDto packetDto)
{
packetService.updatePacket(packetDto);
return "redirect:/packet/modify";
}
HTML form
<form th:action="#{/packet/modify}" method="post" th:object="${packet}" enctype="multipart/form-data">
<input type="text" hidden="hidden" readonly="readonly" th:field="*{id}" />
<input type="text" hidden="hidden" readonly="readonly" th:field="*{filename}" />
<div class="form-group">
<label for="name" class="h3 text-success">Name:</label>
<input id="name" type="text" th:field="*{name}" class="form-control">
</div>
<div class="form-group">
<label for="price" class="h3 text-success">Price:</label>
<input id="price" type="text" th:field="*{price}" class="form-control">
</div>
<div class="form-group">
<label for="description" class="h3 text-success">Description:</label>
<textarea class="form-control" rows="5" th:field="*{description}" id="description"></textarea>
</div>
<div class="form-group">
<label for="image" class="h3 text-success">Image:</label>
<input id="image" type="file" th:field="*{multipartFile}" accept="image/**" class="form-control">
</div>
<div class="form-group">
<label for="channel" class="h2 text-secondary">Channels:</label>
<ul class="list-inline">
<li class="list-inline-item" th:each="c : ${channels}">
<input id="channel" type="checkbox" th:field="*{channelIds}" th:value="${c.id}">
<label th:text="${c.name}"></label>
</li>
</ul>
</div>
<button type="submit" class="btn btn-success btn-lg mr-2">Add</button>
</form>
The http request GET /packet/modify is not being handled in your controller and you are redirecting your POST method to that http request:
return "redirect:/packet/modify";
To solve this you need to do one of the following:
Change the redirect request in your POST to an endpoint that is being handled:
return "redirect:/packet/modify/" + packetDto.getPacketId();
Or, handle that GET endpoint:
#GetMapping("/modify/")
public String retrievePacket(...) { ... }
Hope this helps.
the html code:
<div class="col-md-12">
<span>Select Payment Option</span>
<select class="form-control" name="select1" id="select1"
onchange="fun_showtextbox()">
<option value="x">Cash</option>
<option value="y">Cheque</option>
<option value="z">Mobile Money</option>
</select>
</div>
<div class ="row" style="display:none;" id="mobileno_textbox">
<div class="col-md-12">
<div class="form-group label-floating is-empty is-focused">
<label class ="control-label">Cash</label>
<input type="text" name="select" "id="select"class="form-
control"placeholder="number">
</div>
</div>
</div>
<div class ="row">
<div class="col-md-12">
<div class="form-group label-floating is-empty is-focused">
<label class ="control-label">Amount: </label>
<input type="text" name="select" "id="select"class="form-control"
placeholder="amount">
</div>
</div>
</div>
the div content in number does not show after calling the function.
jquery code:
function fun_showtextbox()
{
var select_status=$('#select1').val();
/* select from select box then show my text box */
if(select_status == "y")
{
$('#mobileno_textbox').show();// By using this id you can show your
content
}
else
{
$('#mobileno_textbox').hide();// otherwise hide
}
}
i don't know what i am doing wrong but div content for id="mobileno_textbox" is not showing?
looks like you may have a few typos. especially your Id. you have "id="select"
anyway I think I have it working here.
https://jsfiddle.net/qLg1fy9d/
js
$(document).ready(function() {
fun_showtextbox();
$('#select1').change(function() {
fun_showtextbox();
})
});
function fun_showtextbox() {
var select_status = $('#select1').val();
/* select from select box then show my text box */
if (select_status == "y") {
$('#mobileno_textbox').show(); // By using this id you can show your
content
} else {
$('#mobileno_textbox').hide(); // otherwise hide
}
}
html
<div class="row">
<div class="col-md-12">
<span>Select Payment Option</span>
<select class="form-control" name="select1" id="select1">
<option value="x">Cash</option>
<option value="y">Cheque</option>
<option value="z">Mobile Money</option>
</select>
</div>
</div>
<div class="row" style="display:none;" id="mobileno_textbox">
<div class="col-md-12">
<div class="form-group label-floating is-empty is-focused">
<label class="control-label">Cash</label>
<input type="text" name="select" id="select" class="form-control" placeholder="number">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group label-floating is-empty is-focused">
<label class="control-label">Amount: </label>
<input type="text" name="select" id="select" class="form-control" placeholder="amount">
</div>
</div>
</div>
It seems like the problem is that you have no jquery included in your html file. This is working with plain js code.
function fun_showtextbox()
{
var select_status = document.getElementById('select1').value;
/* select from select box then show my text box */
if(select_status == "y")
{
document.getElementById('mobileno_textbox').style.display = "block";
}
else
{
document.getElementById('mobileno_textbox').style.display = "none";
}
}
<!DOCTYPE html>
<html>
<body>
<div class="col-md-12">
<span>Select Payment Option</span>
<select class="form-control" name="select1" id="select1"
onchange="fun_showtextbox()">
<option value="x">Cash</option>
<option value="y">Cheque</option>
<option value="z">Mobile Money</option>
</select>
</div>
<div class ="row" style="display:none;" id="mobileno_textbox">
<div class="col-md-12">
<div class="form-group label-floating is-empty is-focused">
<label class ="control-label">Cash</label>
<input type="text" name="select" "id="select"class="form-
control"placeholder="number">
</div>
</div>
</div>
<div class ="row">
<div class="col-md-12">
<div class="form-group label-floating is-empty is-focused">
<label class ="control-label">Amount: </label>
<input type="text" name="select" "id="select"class="form-control"
placeholder="amount">
</div>
</div>
</div>
</body>
</html>
I am trying to display the user profile details when user click on the profile link. I am using eclipse. Also using mvc architecture. No errors occuring but data is not displaying in the jsp file.
CustomerProfileController servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
CustomerViewQuery cvq = new CustomerViewQuery(name);
try {
List<Customer> customers = cvq.list();
request.setAttribute("customers", customers); // Will be available as ${products} in JSP
request.getRequestDispatcher("CustomerProfile.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain vehicles from DB", e);
}
}
CustomerViewQuery file
package dbhelpers;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import models.Customer;
public class CustomerViewQuery {
DBConnection databaseCon = new DBConnection();
String uName;
public CustomerViewQuery(String name) {
this.uName = name;
}
public List<Customer> list() throws SQLException {
List<Customer> customers = new ArrayList<Customer>();
try (
Connection con = databaseCon.dbconnect();
PreparedStatement pst = con.prepareStatement("SELECT * FROM customers WHERE username='\"+uName+\"'");
ResultSet resultSet = pst.executeQuery();
) {
while (resultSet.next()) {
Customer customer = new Customer();
customer.setId(resultSet.getInt("id"));
customer.setName(resultSet.getString("name"));
customer.setEmail(resultSet.getString("email"));
customer.setAddress(resultSet.getString("address"));
customer.setSex(resultSet.getString("sex"));
customer.setBday(resultSet.getString("bday"));
customer.setTelephone(resultSet.getString("telephone"));
customer.setUsername(resultSet.getString("username"));
customer.setPassword(resultSet.getString("password"));
customers.add(customer);
}
}catch(SQLException e) {
e.printStackTrace();
}
return customers;
}
}
Getters and Setters are in the Customer.java file
I get no errors but also nothing is displaying in the CustomerProfile.jsp file. Here is the code
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach items="${customers}" var="customer">
</c:forEach>
<div class="container mt-5"><br>
<form role="form" action="CustomerController" data-toggle="validator" method="post" id="registerForm">
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" value="${customer.name}" placeholder="Name">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" name="email" value="${customer.email}" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<input type="text" name="address" value="${customer.address}" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="sex" class="col-sm-2 col-form-label">Sex</label>
<div class="col-sm-10">
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline1" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline1">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline2" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline2">Female</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="birthdate" class="col-sm-2 col-form-label">Birthdate</label>
<div class="col-sm-10">
<input type="date" name="bday" value="${customer.bday}" placeholder="Birthdate" required>
</div>
</div>
<div class="form-group row">
<label for="telephone" class="col-sm-2 col-form-label">Telephone</label>
<div class="col-sm-10">
<input type="text" name="tele" value="${customer.telephone}" placeholder="Telephone">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-sm-2 col-form-label">Username</label>
<div class="col-sm-10">
<input type="text" name="username" value="${customer.username}" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="passowrd" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" name="password" value="${customer.password}" id="inputPassword" placeholder="Password" data-minlength="6">
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block btn-large">Sign me up.</button>
</form><br>
</div>
Here i changed some things with your code. It should work now. Let me know.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
CustomerViewQuery cvq = new CustomerViewQuery();
try {
List<Customer> customers = cvq.list(name);
request.setAttribute("customers", customers);
request.getRequestDispatcher("CustomerProfile.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain vehicles from DB", e);
}
}
Some changes here too:
public class CustomerViewQuery {
public List<Customer> list(String name) throws SQLException {
List<Customer> customers = new ArrayList<Customer>();
//get connection like this
try(Connection con = DBConnection.dbconnect()) {
PreparedStatement pst = con.prepareStatement("SELECT * FROM customers WHERE username=?;");
pst.setString(1, name); //set name like this (The '1' means first occurance of a question mark '?')
ResultSet resultSet = pst.executeQuery();
while (resultSet.next()) {
Customer customer = new Customer();
customer.setId(resultSet.getInt("id"));
customer.setName(resultSet.getString("name"));
customer.setEmail(resultSet.getString("email"));
customer.setAddress(resultSet.getString("address"));
customer.setSex(resultSet.getString("sex"));
customer.setBday(resultSet.getString("bday"));
customer.setTelephone(resultSet.getString("telephone"));
customer.setUsername(resultSet.getString("username"));
customer.setPassword(resultSet.getString("password"));
customers.add(customer);
}
}catch(SQLException e) {
e.printStackTrace();
}
return customers;
}
}
your forEach JSTL tag was not iterating over anything...
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach items="${customers}" var="customer">
<div class="container mt-5"><br>
<form role="form" action="CustomerController" data-toggle="validator" method="post" id="registerForm">
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" value="${customer.name}" placeholder="Name">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" name="email" value="${customer.email}" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<input type="text" name="address" value="${customer.address}" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="sex" class="col-sm-2 col-form-label">Sex</label>
<div class="col-sm-10">
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline1" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline1">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline2" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline2">Female</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="birthdate" class="col-sm-2 col-form-label">Birthdate</label>
<div class="col-sm-10">
<input type="date" name="bday" value="${customer.bday}" placeholder="Birthdate" required>
</div>
</div>
<div class="form-group row">
<label for="telephone" class="col-sm-2 col-form-label">Telephone</label>
<div class="col-sm-10">
<input type="text" name="tele" value="${customer.telephone}" placeholder="Telephone">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-sm-2 col-form-label">Username</label>
<div class="col-sm-10">
<input type="text" name="username" value="${customer.username}" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="passowrd" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" name="password" value="${customer.password}" id="inputPassword" placeholder="Password" data-minlength="6">
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block btn-large">Sign me up.</button>
</form><br>
</div>
</c:forEach>
EDIT: Here's how you can do it without a loop:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
CustomerViewQuery cvq = new CustomerViewQuery();
try {
//not list required this time, created a new method called 'getCustomer'
Customer customer = cvq.getCustomer(name);
request.setAttribute("customer", customer);
request.getRequestDispatcher("CustomerProfile.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain vehicles from DB", e);
}
}
new method in your CustomerViewQuery Class called 'getCustomer'
public class CustomerViewQuery {
public Customer getCustomer(String name) throws SQLException {
Customer customer = new Customer();
try(Connection con = DBConnection.dbconnect()) {
PreparedStatement pst = con.prepareStatement("SELECT * FROM customers WHERE username=?;");
pst.setString(1, name); //set name like this (The '1' means first occurance of a question mark '?')
ResultSet resultSet = pst.executeQuery();
while (resultSet.next()) {
customer.setId(resultSet.getInt("id"));
customer.setName(resultSet.getString("name"));
customer.setEmail(resultSet.getString("email"));
customer.setAddress(resultSet.getString("address"));
customer.setSex(resultSet.getString("sex"));
customer.setBday(resultSet.getString("bday"));
customer.setTelephone(resultSet.getString("telephone"));
customer.setUsername(resultSet.getString("username"));
customer.setPassword(resultSet.getString("password"));
}
}catch(SQLException e) {
e.printStackTrace();
}
return customer;
}
}
no changes here except removed the JSTL forEach tag as it is not needed anymore.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<div class="container mt-5"><br>
<form role="form" action="CustomerController" data-toggle="validator" method="post" id="registerForm">
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" value="${customer.name}" placeholder="Name">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" name="email" value="${customer.email}" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<input type="text" name="address" value="${customer.address}" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="sex" class="col-sm-2 col-form-label">Sex</label>
<div class="col-sm-10">
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline1" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline1">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline2" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline2">Female</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="birthdate" class="col-sm-2 col-form-label">Birthdate</label>
<div class="col-sm-10">
<input type="date" name="bday" value="${customer.bday}" placeholder="Birthdate" required>
</div>
</div>
<div class="form-group row">
<label for="telephone" class="col-sm-2 col-form-label">Telephone</label>
<div class="col-sm-10">
<input type="text" name="tele" value="${customer.telephone}" placeholder="Telephone">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-sm-2 col-form-label">Username</label>
<div class="col-sm-10">
<input type="text" name="username" value="${customer.username}" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="passowrd" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" name="password" value="${customer.password}" id="inputPassword" placeholder="Password" data-minlength="6">
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block btn-large">Sign me up.</button>
</form><br>
</div>
I encountered this issue on uploading image file. It say's that there is something part is missing and I have no idea. I have searched so many things already but still I couldn't find a solution. I'm trying to insert it in database and store the file in my project directory. It's seems I have missed something.
here is my html:
<form autocomplete="off" th:action="#{/AddCriminal}"
enctype="multipart/form-data" method="post" class="m-t" role="form"
th:object="${criminalRec}" data-toggle="validator">
<h1 class="text-white">Add Criminal</h1>
<div th:if="${info}" class="alert alert-success" role="alert"
th:text=${info}></div>
<div th:if="${infoError}" class="alert alert-danger" role="alert"
th:text="${infoError}"></div>
<div class="row text-center">
<div class="col-md-5">
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}"
class="validation-message alert alert-danger" role="alert"></div>
<div th:if="${#fields.hasErrors('seq_number')}"
th:errors="*{seq_number}"
class="validation-message alert alert-danger" role="alert"></div>
<div th:if="${#fields.hasErrors('comments')}"
th:errors="*{comments}"
class="validation-message alert alert-danger" role="alert"></div>
<div class="form-group">
<label class="text-white">Full Name: </label> <input type="text"
th:field="*{name}" placeholder="Wanted Full name"
class="form-control" required /> <small id="firstnameHelp"
class="form-text text-muted text-white">Full name of the
person</small>
</div>
<div class="form-group">
<label class="text-white">Sequence Number: </label> <input
type="text" th:field="*{seq_number}"
placeholder="Sequence Number" class="form-control" required /> <small
id="firstnameHelp" class="form-text text-muted text-white">Sequence
of the records the Ascending order</small>
</div>
<div class="form-group">
<label class="text-white">Photo: </label> <!-- <input type="file"
th:field="*{photo}" placeholder="Add Photo" class="form-control"
accept="image/*" required /> -->
<input type="file" name="photo" accept="image/*" class="form-control" />
<small id="firstnameHelp" class="form-text text-muted text-white">Upload
Photo</small>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" th:field="*{comments}"
placeholder="Facts" rows="3" required></textarea>
<small id="firstnameHelp" class="form-text text-muted text-white">Facts
about this criminal</small>
</div>
</div>
<div class="col-md-5">
<button type="submit" class="btn btn-primary block full-width m-b">Add
Criminal</button>
</div>
</div>
</form>
my controller:
#RequestMapping(value = "/AddCriminal", method = RequestMethod.POST, consumes = "multipart/form-data")
public ModelAndView processCriminal(ModelAndView modelAndView,
#Valid #ModelAttribute("criminalRec") Criminals criminalRec, #RequestParam("photo") MultipartFile file,
BindingResult bindingResult, HttpServletRequest request)
throws SerialException, SQLException, IOException {
if (bindingResult.hasErrors()) {
modelAndView.setViewName("/admin/addwantedperson");
} else {
storageService.store(file);
System.out.println("FILENAME: " + storageService.getFName());
byte [] byteArr=file.getBytes();
Blob blob = new SerialBlob(byteArr);
criminalRec.setPhoto(blob);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.now();
criminalRec.setDate_added(formatter.format(localDate));
criminalService.saveCriminal(criminalRec);
modelAndView.addObject("info", "Criminal Record Successfully Added!");
modelAndView.addObject("criminalRec", new Criminals());
modelAndView.setViewName("/admin/addwantedperson");
}
return modelAndView;
}
In your Application Properties add spring.http.multipart.enabled=true
I have implemented a registration process where you can send user data to the controller via post request.
The post request works fine, however now I want to pass another value (role, Long) from the form to the controller that is not an attribute of the user model.
That part is not working.
Does anyone know why?
HTML:
<form action="add_user" method="post" class="form-horizontal" th:object="${user}">
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{username}" class="form-control" placeholder="Person ID" type="text" name="id" id="id"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{firstName}" class="form-control" placeholder="First Name" type="text" name="firstname" id="firstname"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{lastName}" class="form-control" placeholder="Last Name" type="text" name="lastname" id="lastname"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{password}" class="form-control" placeholder="Password" type="password" name="password" id="password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<select th:field="${role}" class="form-control" id="role">
<option value="1">Admin</option>
<option value="2" >User</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<button type="submit" class="btn btn-success" value="Submit">Save</button>
</div>
</div>
</form>
Controller:
#RequestMapping(value = "/users", method = RequestMethod.GET)
public String showUsers(Model model)
model.addAttribute("user", new User());
model.addAttribute("role", new Long(2));
return "users";
}
And:
#RequestMapping(value = "/add_user", method = RequestMethod.POST)
public String handleNewUser(#ModelAttribute("user") User user, BindingResult bindingResult, Model model, long role) {
if (user != null) {
System.out.println(role);
userService.save(user);
}
return "redirect:/users";
}
th:field="${role}" means name of field in the model object, not its value. You probably want to write th:value="${role}" instead of this.