I have a jsp page with two textboxes and one submit button. On getting the input value from the form, the value for the second textbox named as "amount" is coming as null.
This is my jsp page -
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" media="screen" href="../../css/bootstrap.css" />
<title>CREDIT / DEBIT Funds</title>
</head>
<body>
<%
String context_path=request.getContextPath();
String navbar_path=context_path+"/pages/navbar.jsp";
%>
<%#include file="../navbar.jsp" %>
<div class="panel panel-primary">
<div class="panel-heading"> CREDIT / DEBIT Funds</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"></h3>
</div>
<div class="panel-body">
<c:if test="${ accountStatus != null}">
<div class="btn-primary">
<div id="status" class="label-primary">${accountStatus}</div>
</div>
</c:if>
<form class="form-horizontal" role="form" method="POST" id="accountFormBean"
commandName="accountFormBean" action="/ira_bank/ExternalUsers/credit_debit">
<div class="form-group">
<label class="radio-inline col-sm-4 control-label">
<input type="radio" name="CreditDebit" id="CreditDebit" value="Credit"> Credit
</label>
<label class="radio-inline col-sm-4 control-label">
<input type="radio" name="CreditDebit" id="CreditDebit" value="Debit"> Debit
</label>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">From/To</label>
<div class="col-sm-7 col-md-7">
<input type="text" name="accountNumber" class="form-control" id="accountNumber" placeholder="From/To Account Number">
</div>
</div>
<div class="form-group">
<label for="inputamount" class="col-sm-2 control-label">Amount</label>
<div class="col-sm-7 col-md-7">
<input type="text" name="amount" class="form-control" id="amount" placeholder="Amount">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-7 col-md-offset-2 col-md-7">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
<script src="../../js/jquery-1.10.2.js"></script>
<script src="../../js/bootstrap.js"></script>
</body>
</html>
And this is the formbean from where i am getting the values -
public class AccountFormBean {
private String amount;
private String accountNumber;
private String CreditDebit;
public void setAccountNumber(String accountNumber){
this.accountNumber = accountNumber;
}
public String getAccountNumber() {
return accountNumber;
}
public void setbalance(String amount) {
this.amount = amount;
}
public String getbalance() {
return amount;
}
public void setCreditDebit(String CreditDebit) {
this.CreditDebit = CreditDebit;
}
public String getCreditDebit() {
return CreditDebit;
}
}
The value for account number is coming fine but it is coming as null for amount.
In your AccountFormBean the getter and setter for amount field are not named correctly. They should be named getAmount() and setAmount(String amount) instead of getbalance() and setbalance(String amount). The framework is usinng getter and setter names to map incoming data to bean fields.
You are using this:
<input type="text" name="amount" class="form-control" id="amount" placeholder="Amount">
Here the name of input field is amount so framework expects you to have getAmount() orsetAmount(int amount) method in your java bean (Note the camelcase as well).
Related
I'm trying to set boxes' elements copied from medicineBox's values like below. Can anyone help me in this. I need to post medicineOrder model to the controller
<tr th:each="medicineBox : ${medicine.medicineBoxes}">
<td class="text-center">
<input type="text" th:field="*{boxes[__${medicineBoxStat.index}__].boxNumber}" th:value="${medicineBox.box.number}" />
</td>
<td class="text-center" th:text="${medicineBox.medicineCount}"></td>
<td><input type="number" th:field="*{boxes[__${medicineBoxStat.index}__].medicineCount}" class="form-control" /></td>
</tr>
I'm using two object here -
medicine and medicineOrder
------------------> Controller method to get the page
#GetMapping("/{medicineId}")
public String loadMedicineDetailPage(#PathVariable("medicineId") long medicineId, Model model) {
model.addAttribute("medicine", service.getMedicineById(medicineId));
model.addAttribute("medicineOrder", new MedicineOrder());
return WebPages.MEDICINE_DETAIL.toString();
}
------------------> thymeleaf html page
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Spring Boot Application</title>
</head>
<body>
<div class="container">
<br/>
<a class="btn btn-primary" th:href="#{/mvc/medicine/list}">Back</a>
<br/>
<br/>
<h3 class="text-center alert alert-success">Medicine Details</h3>
<form class="row g-3" action="#" th:action="#{/mvc/medicine/sell}" method="post" th:object="${medicineOrder}">
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="name" class="form-label">Name</label>
<input type="text" style="background-color:#95edea" disabled class="form-control" id="name" th:field="${medicine.name}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="company" class="form-label">Company</label>
<input type="text" disabled class="form-control" id="company" th:field="${medicine.companyStringName}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="price" class="form-label">Price</label>
<input type="text" disabled class="form-control" id="price" th:field="${medicine.price}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="count" class="form-label">Count</label>
<input type="text" class="form-control" id="count" th:field="${medicine.count}"/>
</div>-->
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="volume" class="form-label">ML</label>
<input type="text" disabled class="form-control" id="volume" th:field="${medicine.volume}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="purchaseDate" class="form-label">Date Purchased</label>
<input type="text" disabled class="form-control" id="purchaseDate" th:field="${medicine.purchaseDate}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="boxNo" class="form-label">Box Number</label>
<input type="text" class="form-control" id="boxNo" th:field="${medicine.boxNumber}"/>
</div>-->
**<input type="hidden" th:field="*{medicineId}" th:value="${medicine.medicineId}"/>**
<table class="table table-bordered">
<tr class="table-primary">
<td>Box Number</td>
<td>Medicine Count</td>
<td>Sell Count</td>
</tr>
<tr th:each="medicineBox : ${medicine.medicineBoxes}">
<td class="text-center">
**<input type="text" th:field="*{boxes[__${medicineBoxStat.index}__].boxNumber}" th:value="${medicineBox.box.number}"** />
</td>
<td class="text-center" th:text="${medicineBox.medicineCount}"></td>
<td><input type="number" th:field="*{boxes[__${medicineBoxStat.index}__].medicineCount}" class="form-control" /></td>
</tr>
</table>
<button class="btn btn-primary" type="submit">Sell</button>
</form>
</div>
</body>
</html>
---------------> Controller method to handle the post request
#PostMapping("/sell")
public String sellMedicine(#ModelAttribute MedicineOrder medicineOrder, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
// error handling
}
service.sellMedicine(medicineOrder);
return "redirect:/mvc/medicine/list";
}
----------------> Class MedicineOrder
package com.example.demo.dto;
import com.example.demo.model.Box;
import java.util.ArrayList;
import java.util.List;
public class MedicineOrder {
private long medicineId;
private List<OrderedBox> boxes = new ArrayList<>();
public long getMedicineId() {
return medicineId;
}
public void setMedicineId(long medicineId) {
this.medicineId = medicineId;
}
public List<OrderedBox> getBoxes() {
return boxes;
}
public void setBoxes(List<OrderedBox> boxes) {
this.boxes = boxes;
}
#Override
public String toString() {
return "MedicineOrder{" +
"medicineId=" + medicineId +
", boxes=" + boxes +
'}';
}
}
package com.example.demo.dto;
public class OrderedBox {
private String boxNumber;
private int medicineCount;
public String getBoxNumber() {
return boxNumber;
}
public void setBoxNumber(String boxNumber) {
this.boxNumber = boxNumber;
}
public int getMedicineCount() {
return medicineCount;
}
public void setMedicineCount(int medicineCount) {
this.medicineCount = medicineCount;
}
#Override
public String toString() {
return "OrderedBox{" +
"boxNumber='" + boxNumber + '\'' +
", medicineCount=" + medicineCount +
'}';
}
}
Not able to get the MedicineOrder.medicineId and medicineBorder.boxes[*].boxNumber from template to model object.
After lot of searching I didn't find any answer which is solving the issue only using thymeleaf.
To solve this issue I had to add two hidden input field for medicineId and boxNumber on medicineOrder object and populate those input field using javascript as below. Anyway if anyone find the solution by only using thymeleaf, please let me know.
Populated those fields using javascript
<script>
function function__02__number__assignment(_element){
var __element = _element.children[0];
var __tElement1 = __element.children[0];
var __tElement2 = __element.children[1];
// Copy value from 2 to 1
__tElement1.value = __tElement2.value;
}
function function__01__box_traverse(){
var rootElement = document.getElementsByClassName('box-stock-details');
for(var __i=0 ; __i < rootElement.length ; __i++) {
function__02__number__assignment(rootElement[__i]);
}
function_01_01_medicineId();
return true;
}
function function_01_01_medicineId(){
var _00_1_id_src = document.getElementById('00-1-id-src');
var _00_1_id_dest = document.getElementById('00-1-id-dest');
_00_1_id_dest.value = _00_1_id_src.value;
}
</script>
updated template file
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Spring Boot Application</title>
</head>
<body>
<div class="container">
<br/>
<a class="btn btn-primary" th:href="#{/mvc/medicine/list}">Back</a>
<br/>
<br/>
<h3 class="text-center alert alert-success">Medicine Details</h3>
<form class="row g-3" action="#" th:action="#{/mvc/medicine/sell}" method="post" th:object="${medicineOrder}">
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="name" class="form-label">Name</label>
<input type="text" style="background-color:#95edea" disabled class="form-control" id="name" th:field="${medicine.name}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="company" class="form-label">Company</label>
<input type="text" disabled class="form-control" id="company" th:field="${medicine.companyStringName}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="price" class="form-label">Price</label>
<input type="text" disabled class="form-control" id="price" th:field="${medicine.price}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="count" class="form-label">Count</label>
<input type="text" class="form-control" id="count" th:field="${medicine.count}"/>
</div>-->
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="volume" class="form-label">ML</label>
<input type="text" disabled class="form-control" id="volume" th:field="${medicine.volume}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="purchaseDate" class="form-label">Date Purchased</label>
<input type="text" disabled class="form-control" id="purchaseDate" th:field="${medicine.purchaseDate}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="boxNo" class="form-label">Box Number</label>
<input type="text" class="form-control" id="boxNo" th:field="${medicine.boxNumber}"/>
</div>-->
<!-- Hidden input to get the value of medicineId from Medicine object -->
<input id="00-1-id-src" type="hidden" th:value="${medicine.medicineId}"/>
<!-- Hidden input to set the medicineId on MedicineOrder object -->
<input id="00-1-id-dest" type="hidden" th:field="*{medicineId}" />
<table class="table table-bordered">
<tr class="table-primary">
<td>Box Number</td>
<td>Medicine Count</td>
<td>Sell Count</td>
</tr>
<tr class="box-stock-details" th:each="medicineBox : ${medicine.medicineBoxes}">
<td class="text-center">
<input hidden th:field="*{boxes[__${medicineBoxStat.index}__].boxNumber}" />
<input disabled class="form-control" type="text" th:value="${medicineBox.box.number}" />
</td>
<td class="text-center" th:text="${medicineBox.medicineCount}"></td>
<td><input type="number" th:field="*{boxes[__${medicineBoxStat.index}__].medicineCount}" class="form-control" /></td>
</tr>
</table>
<button class="btn btn-primary" type="submit" onclick="return function__01__box_traverse()">Sell</button>
</form>
</div>
</body>
<script>
function function__02__number__assignment(_element){
var __element = _element.children[0];
var __tElement1 = __element.children[0];
var __tElement2 = __element.children[1];
// Copy value from 2 to 1
__tElement1.value = __tElement2.value;
}
function function__01__box_traverse(){
var rootElement = document.getElementsByClassName('box-stock-details');
for(var __i=0 ; __i < rootElement.length ; __i++) {
function__02__number__assignment(rootElement[__i]);
}
function_01_01_medicineId();
return true;
}
function function_01_01_medicineId(){
var _00_1_id_src = document.getElementById('00-1-id-src');
var _00_1_id_dest = document.getElementById('00-1-id-dest');
_00_1_id_dest.value = _00_1_id_src.value;
}
</script>
</html>
I started to work with thymeleaf in a basic project. When I want to display a message in the sign up page the th:text does not work. I used already th:text in other .html files and it works there but in the signUp.html doesn't.
Here is my controller where I set the message:
package com.teszt.thymeleaftest.controller;
#Controller
#RequestMapping("/login")
#AllArgsConstructor
public class MemberController {
MembersService membersService;
#GetMapping("/login")
public String showLoginPage(){
return "/login/login";
}
#GetMapping("/signUp")
public String showSignUpPage(Model theModel){
Members theMember = new Members();
theModel.addAttribute("member", theMember);
return "/login/signUp";
}
#PostMapping("/save")
public String saveMember(#ModelAttribute("member") Members theMember, ModelMap modelMap){
Members tempMember = membersService.findByEmail(theMember.getEmail());
if(tempMember != null){
modelMap.addAttribute("error", "Email is already exist!");
return "redirect:/login/signUp";
}else{
membersService.save(theMember);
//prevent duplication
return "redirect:/login/login";
}
}
}
Here is my signUp.html
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<title>Signup</title>
</head>
<body>
<div class="container">
<h3>Signup</h3>
<hr>
<p class="h4 mb-4">Signup</p>
<form action="#" th:action="#{/login/save}" th:object="${member}" method="POST">
<input type="text" th:field="*{firstName}" class="form-control mb-4 col-4" placeholder="First name">
<input type="text" th:field="*{lastName}" class="form-control mb-4 col-4" placeholder="Last name">
<input type="text" th:field="*{email}" class="form-control mb-4 col-4" placeholder="Email">
<input type="password" th:field="*{password}" class="form-control mb-4 col-4" placeholder="Password">
<button type="submit" class="btn btn-info col-2">Save</button>
<p th:text="${error}" />
</form>
<br>
Do you have an account? <a th:href="#{/login/login}">Click here</a>
</div>
</body>
</html>
As I mentioned above this is the only html where the th:text does not works, everywhere else is good.
I hope somebody can help me!
When you use a redirect:, you lose all your model attributes (because it's loading a new page). You need to use a FlashAttribute instead. Like this:
#PostMapping("/save")
public String saveMember(#ModelAttribute("member") Members theMember, ModelMap modelMap, RedirectAttributes redirAttrs){
Members tempMember = membersService.findByEmail(theMember.getEmail());
if(tempMember != null){
redirAttrs.addFlashAttribute("error", "Email is already exist!");
return "redirect:/login/signUp";
}else{
membersService.save(theMember);
//prevent duplication
return "redirect:/login/login";
}
}
I'm pretty new in Spring boot and have some problems.
I have automobile and file, when I add automobile data and save it in db, want to upload the file which is connected to automobile by relationship OneToOne but when save automobile in #PostMapping("/saveAutomobile") I could't take this automobileId and to transfer it to #PostMapping("/uploadFile") to do the connection. Do you have any suggestions?
adding automobile:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<div th:replace="fragments/links"></div>
<meta charset="UTF-8" />
<title>New Brand</title>
<link th:href="#{resources/css/bootstrap.min.css}" rel="stylesheet"></link>
</head>
<body>
<div class="container add shadow">
<h2>New Automobile</h2>
<form th:action="#{/automobile/saveAutomobile}" method="post"
th:object="${automobileForm}">
<div class="row">
<div class="column">
<div class="form-group shadow">
<label class="form-control-label" for="inputBrand"> Brand</label>
<input type="text"
class="form-control form-control-danger box-shadow"
id="inputBrand" th:field="*{brand}" name="brand"
required="required" />
</div>
<div class="form-group shadow">
<label class="form-control-label" for="inputModel"> Model</label>
<input type="text"
class="form-control form-control-danger box-shadow"
id="inputModel" th:field="*{model}" name="model"/>
</div>
</div>
<div style="text-align: center;">
<a th:href="#{/file/uploadFile} + ${automobile?.getId()}"> <input type="submit"
class="btn btn-default box-shadow shadow" />
</a>
</div>
</form>
</div>
<script th:src="#{resources/js/jquery-1.11.1.min.js}"></script>
<script th:src="#{resources/js/bootstrap.min.js}"></script>
</body>
</html>
#PostMapping("/saveAutomobile")
public String saveAutomobile(#Valid final AutomobileForm automobileForm, final BindingResult result) {
if (result.hasErrors()) {
LOG.error("SaveAutomobile Error: " + result);
return "automobile/add";
}
final Automobile automobile = automobileConverter.ConvertToEntity(automobileForm);
if (LOG.isDebugEnabled()) {
LOG.info("Saving client " + automobile);
}
automobileService.save(automobile);
automobileForm.setId(automobile.getId());
return "/files/uploadFile";
}
uploading file:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<div th:replace="fragments/links"></div>
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />
<title>Upload automobile documentation</title>
<link th:href="#{resources/css/bootstrap.min.css}" rel="stylesheet"></link>
</head>
<body>
<div class="container upload shadow">
<h2>Upload automobile documentation</h2>
<form th:action="#{/uploadFile}" method="post"
enctype="multipart/form-data" id="singleUploadForm"
name="singleUploadForm" >
<div class="form-group shadow">
<label class="form-control-label" for="uploadfile">Upload
File:</label> <input id="singleFileUploadInput" type="file" name="file"
class="file-input form-control form-control-danger box-shadow" />
</div>
<button type="submit" class="btn btn-default box-shadow shadow"
id="btnSubmit">Upload</button>
</form>
<div class="upload-response">
<div id="singleFileUploadError"></div>
<div id="singleFileUploadSuccess"></div>
</div>
</div>
<script src="/js/main.js"></script>
</body>
</html>
#Autowired
private FileStorageService DBFileStorageService;
#PostMapping("/uploadFile")
public FileForm uploadFile(#RequestParam("file") MultipartFile file) {
File dbFile = DBFileStorageService.storeFile(file);
return new FileForm(dbFile.getFileName(),
file.getContentType(), file.getSize());
}
You can use models to store data and use it in your HTML page
for example:-
Controller.java
#GetMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
ModelAndView modelAndView = new ModelAndView("viewPage");
modelAndView.addObject("message", "Hello from the controller");
return modelAndView;
}
Test.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<div>Web Application. Passed parameter : th:text="${message}"</div>
</body>
</html>
#PostMapping("/uploadFile")
public ResponseEntity<FileForm> uploadFile(#RequestParam("file") MultipartFile file) {
File dbFile = DBFileStorageService.storeFile(file);
FileForm fileForm = new FileForm(dbFile.getFileName(), file.getContentType(), file.getSize());
return new ResponseEntity<>(fileForm, HttpStatus.OK);
}
When I press the save button ajax does not work.The page reloads.Here is my indx page and my Controller function.
URL is --- http://localhost:8082/spring-test/index
Controller
#RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public String saveUser(#Valid #ModelAttribute("User") User user, BindingResult bindingResult,
ModelMap model, HttpServletRequest request, RedirectAttributes redirectAttrs) {
System.out.println("user: " + user.getUserId());
String type = request.getParameter("update") != null ? request.getParameter("update") : "";
String delete = request.getParameter("delete") != null ? request.getParameter("delete") : "";
if (type.equalsIgnoreCase("update") || delete.equalsIgnoreCase("delete")) {
User userDb = userService.getUserById(user.getUserId());
user.setUserId(userDb.getUserId());
}
if (bindingResult.hasErrors()) {
System.out.println("=====================error======================" + bindingResult.getFieldErrors());
return "index";
}
if (delete.equalsIgnoreCase("delete")) {
userService.deleteUser(user.getUserId());
} else {
userService.saveUser(user);
}
//model.clear();
model.clear();
return "redirect:/index";
}
index.html
<html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org" class="no-js">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#myTable').DataTable();
$('#btnSave').click(function(e) {
var dataUser = $("#name").val();
var dataPass = $("#pwd").val();
var userDdata = {
"name": dateUser,
"pass": dataPass
}
$.ajax({
type: "POST",
url: "/spring-test/saveUser",
data: userData,
success: function(response) {
alert(1)
},
error: function(e) {
alert('Error: ' + e);
}
});
}
});
</script>
</head>
<body>
<div class="container col-sm-12 col-md-12" style="height:20px;background:#85a3e0;">
</div>
<div class="container col-sm-12 col-md-12">
<h3 class="text-center">Super Admin</h3>
<div class="col-md-4 col-sm-4" style="margin-left: 6%;">
<form class="form-horizontal" role="form" th:action="#{/saveUser}" th:object="${user}" method="post">
<div class="form-group">
<label class="control-label col-sm-3" for="pwd">Username:</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="name" placeholder="Enter Name" th:field="*{userName}" />
<input type="hidden" th:field="*{userId}" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pwd">Password:</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="pwd" placeholder="Enter password" th:field="*{password}" />
</div>
</div>
<div class="form-group">
<div class=" col-sm-12 text-right">
<button type="submit" class="btn btn-default" name="cancel" value="cancel">Cancel</button>
<button id="btnSave" type="submit" class="btn btn-primary" name="save" value="save">Save</button>
<button type="submit" class="btn btn-primary" name="update" value="update">Update</button>
<button type="submit" class="btn btn-primary" name="delete" value="delete">Delete</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
Whats the problem here.
After adding the ajax function my dataTable is not appearing also.
Since you already have an action( th:action="#{/saveUser}") for the form submit, it will send the data directly, not via AJAX. In order to make it worked, you need to prevent this default behavior as like below.
$('#btnSave').click(function(e) {
e.preventDefault()
//Then do your stuff
});
It is not working because you have submit button and it directly submits the form.
What you can do it simply remove type="submit" from button and then try.
Vinod
Just try the below
<html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org" class="no-js">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#myTable').DataTable();
$('#btnSave').click(function(e) {
var userData = $("#form1").serializeArray();
$.ajax({
type: "POST",
url: "/spring-test/saveUser",
data: userData,
success: function(response) {
alert(1)
},
error: function(e) {
alert('Error: ' + e);
}
});
}
});
</script>
</head>
<body>
<div class="container col-sm-12 col-md-12" style="height:20px;background:#85a3e0;">
</div>
<div class="container col-sm-12 col-md-12">
<h3 class="text-center">Super Admin</h3>
<div class="col-md-4 col-sm-4" style="margin-left: 6%;">
<form class="form-horizontal" role="form" id="form1" th:action="#{/saveUser}" th:object="${user}" method="post">
<div class="form-group">
<label class="control-label col-sm-3" for="pwd">Username:</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="name" placeholder="Enter Name" th:field="*{userName}" />
<input type="hidden" th:field="*{userId}" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pwd">Password:</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="pwd" placeholder="Enter password" th:field="*{password}" />
</div>
</div>
</form>
<div class="form-group">
<div class=" col-sm-12 text-right">
<button type="submit" class="btn btn-default" name="cancel" value="cancel">Cancel</button>
<button id="btnSave" type="button" class="btn btn-primary" name="save" value="save">Save</button>
<button type="submit" class="btn btn-primary" name="update" value="update">Update</button>
<button type="submit" class="btn btn-primary" name="delete" value="delete">Delete</button>
</div>
</div>
</div>
</div>
</body>
</html>
I am trying to insert data's into database using Spring,Hibernate and MySql. I am getting the following error while inserting data into database
"Neither BindingResult nor plain target object for bean name 'owner' available as request attribute". I tried all possible solutions available but couldn't clear it.
This is my controller
#Controller
public class DataOwnerRegController {
#Autowired(required = true)
DataService dataService;
#RequestMapping(value="/DataOwnerReg",method = RequestMethod.POST)
public String getForm(#ModelAttribute("owner") Model model )
{
model.addAttribute("owner", new Owner());
return "DataOwnerReg";
}
#RequestMapping(value = "/DataOwnerReg")
public ModelAndView registeruser(#ModelAttribute("owner") Owner owner, BindingResult result){
ModelAndView modelAndView = new ModelAndView("DataOwnerReg");
dataService.insertRow(owner);
return modelAndView;
}
}
My View
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>DATA OWNER REGISTRATION</title>
<link href="<c:url value="/resources/theme/css/bootstrap.css"/>" rel="stylesheet" >
<link href="<c:url value="/resources/theme/css/style.css"/>" rel="stylesheet">
<script src="<c:url value="/resources/theme/js/jquery-2.1.4.min.js"/>"> </script>
<script src="<c:url value="/resources/theme/js/bootstrap.mi.js"/>"></script>
<link href='https://fonts.googleapis.com/css?family=Raleway:300' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Bangers' rel='stylesheet' type='text/css'>
</head>
<body class="body-image">
<div>
<nav style="background-color:transparent;border:none" class="navbar navbar-default">
<div class="container">
<ul class="nav navbar-nav">
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/"/>">HOME</a></li>
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/DataOwner"/>">DATAOWNER</a></li>
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/DataOwner"/>">DATA CENTER</a></li>
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/DataOwner"/>">KEY DISTRIBUTION</a></li>
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/DataOwner"/>">ADMINISTRATOR</a> </li>
</ul>
</div>
</nav>
</div>
<div class="container">
<div class="border">
<form:form modelAttribute="owner" method="Post" action="/DataOwnerReg">
<h3 style="text-align:center">Data Owner Registration</h3>
<h2 style="text-align:center">${message}</h2>
<hr style="width:25%"/>
<div class="formation">
<h4>Username:</h4>
<div class="input-group">
<form:input type="text" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="Enter the Username" required="" path="Username" /><div class="input-group-addon"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></div>
</div>
<h4>Password:</h4>
<div class="input-group">
<form:input type="password" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="Enter the Password" required="" path="Password"/><div class="input-group-addon"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></div>
</div>
<h4>Confirm Password:</h4>
<div class="input-group">
<form:input type="password" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="Repeat Password" required="" path="CPassword" /><div class="input-group-addon"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></div>
</div>
<h4>Email Address:</h4>
<div class="input-group">
<form:input type="email" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="me#example.com" required="" path="Email" /><div class="input-group-addon"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span></div>
</div>
<h4>Mobile Number:</h4>
<div class="input-group">
<form:input type="text" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="10 Digit Mobile Number" required="" path="Email" /><div class="input-group-addon"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></div>
</div>
<div>
<input type="submit" style="width:150px;height:45px;margin-top:30px;font-family:Raleway,sans-serif" class="btn btn-success" value="Register"/>
</div>
<br/>
</div>
</form:form>
</div>
</div>
</body>
</html>
Please Help in this.
Thanks in advance
There are a couple things wrong with your controller
First you have the #ModelAttribute on a method argument of the type Model which you shouldn't do. Next the method you expect to be invoked on a GET request is going to be invoked on a POST request so basically there will be no model. Finally in your method that should handle the POST request you are returning a ModelAndView but with an empty model, so at that point there is no model anymore and no Owner object.).
I would suggest to fix your controller in the following way
#Controller
#RequestMapping("/DataOwnerReg")
public class DataOwnerRegController {
private final DataService dataService;
#Autowired
public DataOwnerRegController(DataService DataService) {
this.dataService=dataService;
}
#ModelAttribute
public Owner owner() {
return new Owner();
}
#RequestMapping(method = RequestMethod.GET)
public String get() {
return "DataOwnerReg";
}
#RequestMapping(method = RequestMethod.POST)
public String registeruser(#ModelAttribute("owner") Owner owner, BindingResult result){
dataService.insertRow(owner);
return "DataOwnerReg";
}
}