Attempting to make a delete button in Thymeleaf / Spring MVC - java

Attempting to make a button for much longer than one would assume it takes for a newbie.
The Error message I'm getting is:
'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "${id}"
What am I doing wrong? Thanks in advance.
My Controller:
#Controller
public class BuyerController {
private BuyerService buyerService;
#Autowired
public void setBuyerService(BuyerService buyerService){
this.buyerService = buyerService;
}
#RequestMapping("/add-buyer")
public String showBuyerPager(Model model){
List<Buyer> buyers = buyerService.findAllBuyers();
model.addAttribute("buyers", buyers);
model.addAttribute("buyer", new Buyer());
return "add-buyer";
}
#GetMapping("/showBuyerForm")
public String addBuyerForm(Model model){
model.addAttribute("buyer", new Buyer());
model.addAttribute("buyerId", new Buyer().getBuyerId());
return "add-buyer";
}
#PostMapping("/addBuyer")
public String postBuyerForm(#ModelAttribute("buyer") Buyer buyer, Model model){
buyerService.saveBuyer(buyer);
model.addAttribute("buyer", new Buyer());
return "redirect:/";
}
#PostMapping("/deleteBuyer/{id}")
public String deleteBuyer(#PathVariable Long id){
buyerService.deleteBuyer(id);
return "redirect:/";
}
}
View:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
<link href="styles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<header> Welcome to Toner Stock </header>
<h1>Add Buyer</h1>
<div id="mynav" align="center">
<ul>
<li>Home</li>
<li>Add Buyer</li>
<li>Add Manager</li>
<li>Current Stock</li>
<li>Transactions</li>
<li>Order Form</li>
</ul>
</div>
<div id="display-table" align="center">
<form th:action="#{/addBuyer}" th:object="${buyer}" style="width:100%" method="post">
<table>
<td><label>First Name: </label></td>
<td><input type="text" th:field="*{firstName}"/></td>
<td><label>Last Name: </label></td>
<td><input type="text" th:field="*{lastName}"/></td>
<td><label>Enter Address: </label></td>
<td><input type="text" th:field="*{buyerAddress}"/></td>
<td><input type="submit" value="save"/></td>
</table>
</form>
</div>
<div>
<div>
<table id="info-table" align="center" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
</tr>
<tr th:each="buyer : ${buyers}">
<td th:text="${buyer.firstName}"></td>
<td th:text="${buyer.lastName}"></td>
<td th:text="${buyer.buyerAddress}"></td>
<td>
<form th:action="#{/deleteBuyer/${id}}" th:object="${buyer}" method="post">
<input type="hidden" th:field="${buyer}">Delete</input>
<button type="submit" onClick="return confirm('sure?')"/>
</form>
</td>
</tr>
</table>
</div>
</div>
<div>
<select>
<option th:each="buyer : ${buyers}"
th:text="${buyer.firstName}"
th:value="${buyer.buyerId}"
></option>
</select>
</div>
<div>
<div>
</div>
</div>
</body>
</html>

I'm not a thymeleaf expert but it looks like your form th:action="#{/deleteBuyer/${id}}" should be th:action="#{/deleteBuyer/{id}(id=${buyer.buyerId})}"

Related

HTTP Post Request with nested collection in SpringBoot and Thymeleaf

I am new to Java and I'm currently working on a project with springboot and thymeleaf template engineer. I am having issues making an HTTP POST request with nested Set Collection.
My Java Classes are
User Class
import java.util.Set;
public class User {
private String name;
private String school;
private String bestSubject;
private Set<Work> work;
*//constructors, getters and setters*
}
Work Class
public class Work {
private String companyName;
private String faxNumber;
private String location;
*//constructors, getters and setters*
}
Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class UserController {
#Autowired
private UserService userService;
#GetMapping(value = "/user-register")
public String showUser(Model model) {
User users = new User();
model.addAttribute("users", userService.getUsersList());
return "userPage";
}
#PostMapping(value = "/user-details")
public String createUser(#ModelAttribute("users") User user){
System.out.println(user);
return "userResult";
}
}
Views
userPage.html
<form action="#" th:action="#{/user-details}" method="post" th:object="${users}">
<div class="row">
<div class="col-4">
<label for="name" class="col-form-label">Full Name:</label>
<input type="text" id="name" th:field="*{name}" class="form-control">
</div>
<div class="col-4">
<label for="school" class="col-form-label">School:</label>
<input type="text" id="school" th:field="*{school}" class="form-control">
</div>
<div class="col-4">
<label for="bestSubject" class="col-form-label">Best Subject:</label>
<input type="text" id="bestSubject" th:field="*{bestSubject}" class="form-control">
</div>
</div>
<!--BUTTON TO ADD AND DELETE FIELDS-->
<div class="row mt-4 mb-1">
<div class="col d-flex justify-content-between">
<div onclick="createField()" class="btn btn-primary float-start">Create row</div>
<div onclick="deleteField()" class="btn btn-danger float-end">Delete row</div>
</div>
</div>
<!--FIELDS LABEL-->
<div class="row">
<div class="col-4">
<label for="companyName" class="col-form-label">Company Name:</label>
</div>
<div class="col-4">
<label for="faxNumber" class="col-form-label">Fax Number:</label>
</div>
<div class="col-4">
<label for="location" class="col-form-label">Location:</label>
</div>
</div>
<table class="table table-borderless mt-0" id="userTable">
<tbody id="tableBody">
<tr th:each="user : ${users.work}">
<td>
<input type="text" id="companyName" th:field="*{user.companyName}" class="form-control">
</td>
<td>
<input type="text" id="faxNumber" th:field="*{user.faxNumber}" class="form-control">
</td>
<td>
<input type="text" id="location" th:field="*{user.location}" class="form-control">
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-warning">
SUBMIT
</button>
</form>
UserResult.html
<p>Full Name: <span th:text="${users.name}"></span></p>
<p>University: <span th:text="${users.school}"></span></p>
<p>Best Subject: <span th:text="${users.bestSubject}"></span></p>
<table class="table table-striped .table-hover mt-1">
<thead>
<tr>
<th scope="col">Company Name</th>
<th scope="col">Fax Number</th>
<th scope="col">Address</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users.work}">
<td th:text="${user.companyName}">
</td>
<td th:text="${user.faxNumber}">
</td>
<td th:text="${user.location}">
</td>
</tr>
</tbody>
</table>
My QUESTION IS
I keep getting User{name='...', school='...', bestSubject='...', work { **'null**' }}
Instead of
{
name: '...'
school: '...'
work: {
company_name: '...',
fax_number: '...',
location: '...'
}
}
How do I ensure my Set collection returns the inputed data from the fields instead of null datatype?

Spring Application: Problem Parsing Form Object To Controller Using #Model attribute. Error org.attoparser.ParseException:Field

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" type="text/css" media="all" th:href="#{/css/bootstrap.min.css}">
<title>Home</title>
</head>
<body class="p-3 mb-2 bg-light text-black">
<div class="container">
<div id="logoutDiv">
<h1 th:text="${'Welcome ' + name}">Name</h1>
<form action="#" th:action="#{/logout}"method="POST">
<button type="submit" class="btn btn-secondary float-right">Logout</button>
</form>
</div>
<div id="contentDiv" style="clear: right;">
<nav style="clear: right;">
<div class="nav nav-tabs" id="nav-tab" role="tablist">
<a class="nav-item nav-link active" id="nav-files-tab" data-toggle="tab" href="#nav-files" role="tab" aria-controls="nav-files" aria-selected="true">Files</a>
<a class="nav-item nav-link" id="nav-notes-tab" data-toggle="tab" href="#nav-notes" role="tab" aria-controls="nav-notes" aria-selected="false">Notes</a>
<a class="nav-item nav-link" id="nav-credentials-tab" data-toggle="tab" href="#nav-credentials" role="tab" aria-controls="nav-credentials" aria-selected="false">Credentials</a>
</div>
</nav>Upload<
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-files" role="tabpanel" aria-labelledby="nav-files-tab">
<p th:text="${message}" th:if="${message ne null}" class="alert alert-primary"></p>
<form action="#" enctype="multipart/form-data" th:action="#{'/file/uploadFile'}" th:method="POST" >
<div class="container">
<div class="row" style="margin: 1em;">
<div class="col-sm-2">
<label for="fileUpload">Upload a New File:</label>
</div>
<div class="col-sm-6">
<input type="file" class="form-control-file" id="fileUpload" name="fileUpload">
</div>
<div class="col-sm-4">
<button type="submit" class="btn btn-dark">/button>
</div>
</div>
</div>
</form>
<div class="table-responsive">
<table class="table table-striped" id="fileTable">
<thead>
<tr>
<th style="width: 20%" scope="col"></th>
<th style="width: 80%" scope="col">File Name</th>
</tr>
</thead>
<tbody>
<tr th:each="file : ${files}">
<td>
<a target="_blank" class="btn btn-success" th:href="#{/file/{filename}(fileName = ${file.filename})}">View</a>
<a class="btn btn-danger" th:href="#{/file/delete{filename}(filename = ${file.filename})}" >Delete</a>
</td>
<th scope="row" th:text="${file.filename}" ></th>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane fade" id="nav-notes" role="tabpanel" aria-labelledby="nav-notes-tab">
<button style="margin: 0.25em;" type="button" class="btn btn-info float-right" onclick="showNoteModal()">
+ Add a New Note
</button>
<div class="table-responsive">
<table class="table table-striped" id="userTable">
<thead>
<tr>
<th style="width: 20%" scope="col"></th>
<th style="width: 20%" scope="col">Title</th>
<th style="width: 60%" scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr th:each="note : ${notes}">
<td>
<button id="edit-note" type="button" class="btn btn-success"
th:attr="data-id=${note.getNoteId},
data-title=${note.getNoteTitle},
data-description=${note.getNoteDescription}"
onclick="showNoteModal (this.getAttribute('data-id'),this.getAttribute('data-title'),this.getAttribute('data-description'))">Edit/View</button>
<a id="delete-note" class="btn btn-danger" th:href="#{/note/delete/{noteId}(noteId = ${note.getNoteId()})}">Delete</a>
</td>
<th id="notetitle" scope="row" th:text="${note.getNoteTitle()}">Example Title</th>
<td id="notedescription" th:text="${note.getNoteDescription()}">Example Description </td>
</tr>
</tbody>
</table>
</div>
<div class="modal fade" id="noteModal" tabindex="-1" role="dialog" aria-labelledby="noteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="noteModalLabel">Note</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
-Here is the error that I get-
<form action="#" method="POST" th:action="#{/note/add}" th:object="${Notes}">
<input type="hidden" name="noteId" id="note-id">
<div class="form-group">
<label for="note-title" class="col-form-label">Title</label>
<input type="text" name= "noteTitle" class="form-control" id="note-title" maxlength="20" required th:field="*{noteTitle}">
</div>
<div class="form-group">
<label for="note-description" class="col-form-label">Description</label>
<textarea class="form-control" name="noteDescription" id="note-description" rows="5" maxlength="1000" required th:field="*{noteDescription}"></textarea>
</div>
<button id="noteSubmit" type="submit" class="d-none"></button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="$('#noteSubmit').click();">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="nav-credentials" role="tabpanel" aria-labelledby="nav-credentials-tab">
<button style="margin: 0.25em;" type="button" class="btn btn-info float-right" onclick="showCredentialModal()">
+ Add a New Credential
</button>
<div class="table-responsive">
<table class="table table-striped" th:object="${credentials}" id="credentialTable">
<thead>
<tr>
<th style="width: 20%" scope="col"></th>
<th style="width: 35%" scope="col">URL</th>
<th style="width: 20%" scope="col">Username</th>
<th style="width: 25%" scope="col">Password</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<button type="button" class="btn btn-success">Edit</button>
<a class="btn btn-danger">Delete</a>
</td>
<th scope="row">Example Credential URL</th>
<td>Example Credential Username</td>
<td>Example Credential Password</td>
</tr>
</tbody>
</table>
</div>
<div class="modal fade" id="credentialModal" tabindex="-1" role="dialog" aria-labelledby="credentialModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="credentialModalLabel">Credential</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="#" method="POST">
<input type="hidden" name="credentialId" id="credential-id">
<div class="form-group">
<label for="note-title" class="col-form-label">URL</label>
<input type="text" name= "url" class="form-control" id="credential-url" maxlength="100" required>
</div>
<div class="form-group">
<label for="note-title" class="col-form-label">Username</label>
<input type="text" name= "username" class="form-control" id="credential-username" maxlength="30" required>
</div>
<div class="form-group">
<label for="note-title" class="col-form-label">Password</label>
<input type="text" name= "password" class="form-control" id="credential-password" maxlength="30" required>
</div>
<button id="credentialSubmit" type="submit" class="d-none"></button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="$('#credentialSubmit').click();">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:src="#{/js/jquery-slim.min.js}"></script>
<script th:src="#{/js/popper.min.js}"></script>
<script th:src="#{/js/bootstrap.min.js}"></script>
<!--For opening the note modal-->
<script type="text/javascript">
// For opening the note modal
function showNoteModal(noteId, noteTitle, noteDescription) {
$('#note-id').val(noteId ? noteId : '');
$('#note-title').val(noteTitle ? noteTitle : '');
$('#note-description').val(noteDescription ? noteDescription : '');
$('#noteModal').modal('show');
}
// For opening the credentials modal
function showCredentialModal(credentialId, url, username, password) {
$('#credential-id').val(credentialId ? credentialId : '');
$('#credential-url').val(url ? url : '');
$('#credential-username').val(username ? username : '');
$('#credential-password').val(password ? password : '');
$('#credentialModal').modal('show');
}
</script>
</body>
</html>
-I get an error when trying to parse the Note Form into my Note Controller. I try to parse my model object Notes in the form in my HTML home form into the Controller but it can not except the fields from the form. My first error is this:
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "home" - line 109, col 148), Line 109 is the fields from the form
I also get a second error: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'Notes' available as request attribute-
--- Note Controller ---
#Controller
#RequestMapping("note")
public class NoteController {
private NoteService noteServices;
private UserService userService;
public NoteController(NoteService noteServices, UserService userService) {
this.noteServices = noteServices;
this.userService = userService;
}
// Add an new note
#PostMapping("add")
public String addNote(#ModelAttribute(value="Notes")Notes Notes, Authentication authentication, Model model) throws IOException {
String userName = authentication.getName();
User user = userService.getUser(userName);
Integer userid = user.getId();
if(Notes.getNoteId() == null){
noteServices.addNote(Notes,userid);
}else{
noteServices.editNote(Notes);
}
return "result";
}
#GetMapping("/delete/{noteId:.+}")
public String deleteNote(#PathVariable Integer noteId, Authentication authentication, RedirectAttributes redirectAttributes){
noteServices.deleteNote(noteId);
redirectAttributes.addFlashAttribute("deleteNoteSuccess","Note deleted successfully.");
return "redirect:/result";
}
private Integer getUserId(Authentication authentication) {
String userName = authentication.getName();
User user = userService.getUser(userName);
return user.getId();
}
}
---
--- POJO Model ---
public class Notes {
private Integer noteId;
private String noteTitle;
private String noteDescription;
private Integer userId;
public Notes(String noteTitle, String noteDescription, Integer userId) {
this.noteTitle = noteTitle;
this.noteDescription = noteDescription;
this.userId = userId;
}
public Integer getNoteId() {
return noteId;
}
public void setNoteId(Integer noteId) {
this.noteId = noteId;
}
public String getNoteTitle() {
return noteTitle;
}
public void setNoteTitle(String noteTitle) {
this.noteTitle = noteTitle;
}
public String getNoteDescription() {
return noteDescription;
}
public void setNoteDescription(String noteDescription) {
this.noteDescription = noteDescription;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}

Retrieve input(s) from DataTable

Need some advice how should I retrieve a list of exhibits.
In my html template below, I only put one record of exhibit. If i were to put additional rows/records of exhibit, how do i go about mapping them to the controller.
HTML Template
<h3>Exhibit Details</h3>
<div class="table-responsive">
<table id="exhibitTable"
class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Exhibit Type</th>
<th>Description</th>
<th>Marking</th>
<th>Remarks</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group col-md-3">
<div class="cols-sm-10">
<select class="form-control selectpicker cols-md-3"
th:value="${exhibit.exhibitType}" id="exhibitType"
name="exhibitType" roleId="exhibitType">
<option value="">Select Type</option>
<option>Desktop</option>
<option>Laptop</option>
<option>Mobile Device</option>
<option>Portable Storage</option>
<option>Server</option>
<option>Video System</option>
<option>Save As</option>
<option>Others</option>
</select>
</div>
</div>
</td>
<td>
<div class="form-group col-md-3">
<input type="text" name="exhibitDescription"
id="exhibitDescription"
th:value="${exhibit.exhibitDescription}" />
</div>
</td>
<td>
<div class="form-group col-md-3">
<input type="text" name="exhibitMarking" id="exhibitMarking"
th:value="${exhibit.exhibitMarking}" />
</div>
</td>
<td><div class="form-group col-md-3">
<input type="text" name="exhibitRemarks" id="exhibitRemarks"
th:value="${exhibit.exhibitRemarks}" />
</div></td>
</tr>
</tbody>
</table>
</div>
Controller
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerIncidentPost(#ModelAttribute("incident") Incident incident,
#ModelAttribute("exhibit") Exhibit exhibit, Principal principal) throws Exception {
long year = Calendar.getInstance().get(Calendar.YEAR);
incident.setIncidentYear(year + "");
Long refNo = incidentService.findMaxRefNoCurrentYear(year + "");
if (refNo == null)
refNo = (long) 1;
else
refNo += 1;
incident.setIncidentRefNo(refNo);
incident.setIncidentStatus(Incident.INCIDENT_REGISTERED);
incident.setIncidentOpeningTimestamp(new Date());
User user = userService.findByUsername(principal.getName());
incident.setIncidentCreatedBy(user);
incidentService.createIncident(incident);
exhibitService.createExhibit(exhibit);
return "redirect:/incident";
}
I've attempted to add the following to my template
<tr data-th-each="exhibit:${exhibitList}">
and the following to my controller
#ModelAttribute("exhibitList") ArrayList<Exhibit> exhibitList
but did not work.
Thanks in advance.
I can only assume this is vb.net since you didn't specify. You need to pass in the complete dataset to the page. Each item in the dataset will be one pre-loaded instance of the model. Then you can do a for each loop on the page itself and generate the html dynamically. Hope this helps.

Method Not Allowed, status=405 trying to make a delete entity button

Not sure what I'm doing wrong on this one. Attempting to make a button that can delete added entities from database. I'm getting a 405 error but I am not sure if I'm getting this because of something I'm doing in the controller or something badly I wrote in thymeleaf. Thanks for any help.
Controller:
#Controller
public class BuyerController {
private BuyerService buyerService;
#Autowired
public void setBuyerService(BuyerService buyerService){
this.buyerService = buyerService;
}
#RequestMapping("/add-buyer")
public String showBuyerPager(Model model){
List<Buyer> buyers = buyerService.findAllBuyers();
model.addAttribute("buyers", buyers);
model.addAttribute("buyer", new Buyer());
return "add-buyer";
}
#GetMapping("/showBuyerForm")
public String addBuyerForm(Model model){
model.addAttribute("buyer", new Buyer());
model.addAttribute("buyerId", new Buyer().getBuyerId());
return "add-buyer";
}
#PostMapping("/addBuyer")
public String postBuyerForm(#ModelAttribute("buyer") Buyer buyer, Model model){
buyerService.saveBuyer(buyer);
model.addAttribute("buyer", new Buyer());
return "redirect:/";
}
#GetMapping("/deleteBuyer")
public String deleteBuyer(#RequestParam("buyerid") Long id){
buyerService.deleteBuyer(id);
return "redirect:/";
}
}
View:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
<link href="styles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<header> Welcome to Toner Stock </header>
<h1>Add Buyer</h1>
<div id="mynav" align="center">
<ul>
<li>Home</li>
<li>Add Buyer</li>
<li>Add Manager</li>
<li>Current Stock</li>
<li>Transactions</li>
<li>Order Form</li>
</ul>
</div>
<div id="display-table" align="center">
<form th:action="#{/addBuyer}" th:object="${buyer}" style="width:100%" method="post">
<table>
<td><label>First Name: </label></td>
<td><input type="text" th:field="*{firstName}"/></td>
<td><label>Last Name: </label></td>
<td><input type="text" th:field="*{lastName}"/></td>
<td><label>Enter Address: </label></td>
<td><input type="text" th:field="*{buyerAddress}"/></td>
<td><input type="submit" value="save"/></td>
</table>
</form>
</div>
<div>
<div>
<table id="info-table" align="center" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
</tr>
<tr th:each="buyer : ${buyers}">
<td th:text="${buyer.firstName}"></td>
<td th:text="${buyer.lastName}"></td>
<td th:text="${buyer.buyerAddress}"></td>
<td>
<form th:action="#{/deleteBuyer}" th:object="${buyer}" method="post">
<input type="hidden" name="buyerid" id="buyerid" value="${buyer.buyerId}"/>
<input type="submit" value="Delete" onClick="return confirm('sure?')"/>
</form>
</td>
</tr>
</table>
</div>
</div>
<div>
<select>
<option th:each="buyer : ${buyers}"
th:text="${buyer.firstName}"
th:value="${buyer.buyerId}"
></option>
</select>
</div>
<div>
<div>
</div>
</div>
</body>
</html>
I don't know much about Thymeleaf but you can keep it simpler and change your front-end code from form to basic link :
<c:url var="deleteBuyer" value="/DeleteBuyer">
<c:param name="buyerId" value="${buyer.buyerId}" />
</c:url>
<a class="simpleLink" href="${deleteBuyer}">delete</a>
And handle it in your controller :
` #GetMapping("/DeleteBuyer")
public String deleteAnswer(#RequestParam("buyerId") int theId) {
buyerService.deleteBuyer(theId);
return "redirect:/";
}`
I hope this help you.
Change the
<form th:action="#{/deleteBuyer}" th:object="${buyer}" method="post">
To GET to conform with the Spring request mapping
<form th:action="#{/deleteBuyer}" th:object="${buyer}" method="get">
Here are all available HTTP Methods

Struts form automatically submitted when using validate() method

I am using struts 1.2. My struts flow is working properly but when I am using validate() method of action form for validation. my form is automatically submitted. and this validation method get called.
I am not sure this is normal behavior of struts or some configuration are missing in my application.
Please help me to understand it.
following are the config and code
<action path="/Postaddd"
type="bseller.postadd.PostaddAction"
parameter="dispatch"
scope="request"
validate="true"
name="PostadddForm">
<forward name="posterror" path="ordererror.page"/>
<forward name="successPost" path="bseller.successPost.page"/>
</action> public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
{
Logger log= Logger.getLogger("BSELLER_APPLICATION");
log.info("validate method called");
ActionErrors errors = new ActionErrors();
log.info("Email Id: " + getEmailid());
if(!Validation.isValidEmailAddress(getEmailid()))
{
errors.add("emailid", new ActionMessage("prompt.email.error"));
}
if(!Validation.isPhoneNumberValid(getMobile()))
{
errors.add("mobile", new ActionMessage("prompt.contactno.error"));
}
if(!Validation.isNumeric(getPrice()))
{
errors.add("price", new ActionMessage("prompt.price.error"));
}
return errors;
}
///////////////
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<%# taglib uri="/WEB-INF/displaytag.tld" prefix="display" %>
<%# taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%# taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%# taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<%# taglib uri="/WEB-INF/c.tld" prefix="c"%>
<%# page import="bseller.utils.*" %>
<%# page import="java.util.*" %>
<%#page import="bseller.utils.CategorydetailObject"%>
<%#page import="org.apache.struts.taglib.logic.IterateTag"%><head>
<title><bean:message key="homepage.title" /></title>
<html:base />
<style type="text/css">
#import url("<%=request.getContextPath()%>/css/main.css");
#import url("<%=request.getContextPath()%>/css/submitpost.css");
</style>
<script language="javascript" src="jquery_mini.js"></script>
<script language="javascript" src="jquery.dimensions.js"></script>
<script language="javascript" src="js/Ajax_Function.js"></script>
<script language="javascript">
var name = "#floatMenu";
var menuYloc = null;
$(document).ready(function(){
menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px")))
$(window).scroll(function () {
offset = menuYloc+$(document).scrollTop()+"px";
$(name).animate({top:offset},{duration:500,queue:false});
});
});
</script>
<script>
function ret_home()
{
alert("home");
return false;
}
function ret_aboutus()
{
alert("about us");
return false;
}
function ret_contactus()
{
alert("contact us");
return false;
}
function getSubcatValue(categoryValue)
{
//alert(document.getElementById("categorySelect").Value);
document.getElementById("categorySelect").Value =categoryValue;
//alert(document.getElementById("categorySelect").Value);
//alert(categoryValue);
//var data="catvalue="+categoryValue;
//alert(data);
//datafromajax="";
// alert("before1"+datafromajax);
var url="Subcategory_Ajax.jsp?catvalue="+categoryValue;
sendRequest(url);
//alert("after"+datafromajax);
//datafromajax="";
document.getElementById("categorySelect").Value="";
}
/*function setUploadImageOption(ordertype);
{
if(ordertype=="Required")
{
//document.getElementById("UploadImage").visible= false;
document.getElementById('UploadImage').style.visibility = 'hidden';
}
}*/
function onchangeSubcat(subcatValue)
{
// alert(subcatValue);
//alert(document.getElementById("subCatSelect").Value);
document.getElementById("subCatSelect").Value =subcatValue;
//alert(document.getElementById("subCatSelect").Value);
//subcatValue=subcatValue;
}
//populatedropdown
</script>
<style type="text/css">
body {
height:2000px;
color:#111;
font:10px "Lucida Grande", "Lucida Sans", "Trebuchet MS", verdana, sans-serif;
}
#floatMenu {
position:absolute;
top:200px;
left:55%;
margin-left:235px;
width:200px;
}
#floatMenu ul {
margin-bottom:20px;
}
#floatMenu ul li a {
display:block;
border:1px solid #999;
background-color:#000;
background:'images/tab_bg1.gif'
border-left:6px solid #999;
text-decoration:none;
color:#ccc;
padding:5px 5px 5px 25px;
}
#floatMenu ul li a:hover {
color:#fff;
background-color:#333333;
}
#floatMenu ul.menu1 li a:hover {
border-color:#09f;
}
#floatMenu ul.menu2 li a:hover {
border-color:#9f0;
}
#floatMenu ul.menu3 li a:hover {
border-color:#f09;
}
</style>
</head>
<body>
<span id="er"></span>
<%!
List l;
HashMap<String ,ArrayList<CategorydetailObject>> hm =null; %>
<%
try
{
hm =(HashMap<String ,ArrayList<CategorydetailObject>>)config.getServletContext().getAttribute("PRODUCTS");
}
catch(Exception e)
{
}
%>
<input type="hidden" name="subcatfromajax" id="subcatfromajax"></input>
<DIV class=city><DIV id=welcome></DIV><DIV id=main><DIV id=block><DIV id=header><font size=4 color=blue >
Post Your Advertisement</DIV><DIV class=blank5></DIV><DIV class=blank5></DIV>
<html:messages id="" />
<html:form action="/Postaddd.do?dispatch=submitPost" method="post" enctype="multipart/form-data" >
<TABLE cellSpacing=0 cellPadding=0 width='98%'background='images/background_city.gif' border=0><TBODY>
<TR>
<TD><div class="post_ad_fonts">Email</div><div style="float:left">
<input style="width:162px" type="text" maxlength="64" name="emailid" id="emailid" class="post_ad_field" value='' />
</div>
<div class="blank10"></div>
</TD>
</TR>
<TR>
<TD><DIV id=bb1><div class="post_ad_fonts">City</div><div style="float:left">
<select class="post_ad_field" style="width:165px" name='citySelectBox' id='citySelectBox'>
<option id='0' name='0' value='0'>Select City</option>
<option name='22' id='22' value='Ahmedabad' >Ahmedabad</option><option name='211001' id='211001' value='Allahabad' >Allahabad</option><option name='23' id='23' value='Bangalore' >Bangalore</option><option name='462001' id='462001' value='Bhopal' >Bhopal</option><option name='24' id='24' value='Chandigarh' >Chandigarh</option><option name='25' id='25' value='Chennai' >Chennai</option><option name='26' id='26' value='Coimbatore' >Coimbatore</option><option name='27' id='27' value='Delhi' >Delhi</option><option name='403108' id='403108' value='Goa' >Goa</option><option name='132222' id='132222' value='Gurgaon' >Gurgaon</option><option name='580020' id='580020' value='Hubli' >Hubli</option><option name='28' id='28' value='Hyderabad' >Hyderabad</option><option name='142222' id='142222' value='Indore' >Indore</option><option name='152222' id='152222' value='Jaipur' >Jaipur</option><option name='144001' id='144001' value='Jalandhar' >Jalandhar</option><option name='831001' id='831001' value='Jamshedpur' >Jamshedpur</option><option name='421301' id='421301' value='Kalyan' >Kalyan</option><option name='208001' id='208001' value='Kanpur' >Kanpur</option><option name='29' id='29' value='Kochi' >Kochi</option><option name='30' id='30' value='Kolkata' >Kolkata</option><option name='162222' id='162222' value='Lucknow' >Lucknow</option><option name='141001' id='141001' value='Ludhiana' >Ludhiana</option><option name='625001' id='625001' value='Madurai' >Madurai</option><option name='575001' id='575001' value='Mangalore' >Mangalore</option><option name='31' id='31' value='Mumbai' >Mumbai</option><option name='32' id='32' value='Mysore' >Mysore</option><option name='172222' id='172222' value='Nagpur' >Nagpur</option><option name='422001' id='422001' value='Nashik' >Nashik</option><option name='400701' id='400701' value='NaviMumbai' >NaviMumbai</option><option name='201301' id='201301' value='Noida' selected>Noida</option><option name='800001' id='800001' value='Patna' >Patna</option><option name='33' id='33' value='Pune' >Pune</option><option name='360001' id='360001' value='Rajkot' >Rajkot</option><option name='182222' id='182222' value='Surat' >Surat</option><option name='400601' id='400601' value='Thane' >Thane</option><option name='620015' id='620015' value='Trichy' >Trichy</option><option name='695001' id='695001' value='Trivandrum' >Trivandrum</option><option name='390001' id='390001' value='Vadodara' >Vadodara</option><option name='520001' id='520001' value='Vijayawada' >Vijayawada</option><option name='531001' id='531001' value='Vizag' >Vizag</option></select>
<input type='hidden' name='city' id='city' value='201301'/>
</div>
<div class="blank10"></div>
</div>
</TD></TR>
<TR>
<TD>
<div class="post_ad_fonts">Category</div>
<div style="float:left">
<select class="post_ad_field" style="width:165px" name='categorySelect' id='categorySelect'" onchange="getSubcatValue(this.value);">
<option id='0' value='0'>Select Category</option>
<%
Set<Map.Entry<String,ArrayList<CategorydetailObject>>> set =hm.entrySet();
for(Map.Entry<String,ArrayList<CategorydetailObject>> me: set)
{
String cat= me.getKey();
%>
<option name="<%=cat %>" id="<%=cat %>" value="<%=cat %>"> <%=cat %></option>
<%
}
%>
</select>
<input type='hidden' name='categorySelect' id='categorySelect' value=''/>
</div>
<div class="blank10"></div>
</TD>
</TR>
<TR>
<TD>
<div class="post_ad_fonts">SubCategory</div>
<div style="float:left">
<select class="post_ad_field" style="width:165px" name='subCatSelect' id='subCatSelect' onchange="onchangeSubcat(this.value);">
<option id='0' value='0'>Select SubCategory</option>
</select>
<input type='hidden' name='subCatSelect' id='subCatSelect' value=''/>
</div>
<div class="blank10"></div>
</TD>
</TR>
<TR>
<TD>
<DIV id=bb1><div class="post_ad_fonts">Head Line</div>
<div style="float:left">
<input style="width:440px" type="text" maxlength="64" name="headline" id="headline" class="post_ad_field" value='' />
</div>
<div class="blank10"></div>
</div>
</TD>
</TR>
<TR>
<TD>
<DIV id=bb1><div class="post_ad_fonts">Description</div>
<div style="float:left;width :440px;">
<table border="0" style="margin:0px"><tr><td><div id="showbar">Loading Html Editor...<img src="images/ajax_loader.gif" alt="loading"/></div></td></tr></table>
<textarea name="description" id="description " onfocus="if(this.value=='Adding more detail here will help you get more responses.')this.value='';" style="width:440px;height:170px">Adding more detail here will help you get more responses.</textarea>
</div>
</div>
</TD>
</TR>
<TR>
<TD>
<div class="post_ad_fonts">Mobile No.<br/><span style="font-weight:normal">(Optional)</span></div>
<div style="float:left">
<input style="width:162px" type="text" maxlength="14" name="mobile" id="mobile" class="post_ad_field" value="" />
</div>
<div class="blank10"></div>
</TD>
</TR>
<TR>
<TD>
<div class="post_ad_fonts">Price<br/><span style="font-weight:normal">(Optional)</span></div>
<div style="float:left">
<input style="width:162px" type="text" maxlength="14" name="price" id="price" class="post_ad_field" value="" />
</div>
<div class="blank10"></div>
</TD>
</TR>
<TR>
<TD>
<div class="post_ad_fonts">Owner type<br/></div>
<div style="float:left">
<select class="post_ad_field" style="width:165px" name='owner' id='owner'>
<option id='0' name='0' value='0'>Individual</option>
<option name='22' id='22' value='Ahmedabad' >Broker</option></select>
<input type='hidden' name='ownertype' id='ownertype' value='Individual'/>
</div>
<div class="blank10"></div>
</TD>
</TR>
<TR>
<TD>
<div class="post_ad_fonts">Order type<br/></div>
<div style="float:left">
<select class="post_ad_field" style="width:165px" name='order' id='order'">
<option id='0' name='0' value='Available'>Available</option>
<option name='22' id='22' value='Required' >Required</option></select>
<input type='hidden' name='ordertype' id='ordertype' value='Available'/>
</div>
<div class="blank10"></div>
</TD>
</TR>
<TR>
<TD>
<div class="post_ad_fonts">Upload Image<br/></div>
<div style="float:left" id="UploadImage">
<html:file property="image1"></html:file>
<html:file property="image2"></html:file>
<html:file property="image3"></html:file>
<input type="file" name="image4">
</div>
<div class="blank10"></div>
</TD>
</TR>
<tr><td><div class="post_ad_fonts"><br/></div><div style="float:middle"><html:submit>POST ORDER</html:submit></div> </td></tr>
</TBODY></TABLE></html:form></DIV></DIV></DIV><DIV class=blank10></DIV></DIV></DIV>
<div id="floatMenu">
<ul class="menu1">
<li> Home </li>
</ul>
<ul class="menu2">
<li> About Us </li>
<!--<li> </li>
<li> </li>-->
</ul>
<ul class="menu3">
<li> Contact Us </li>
</ul>
</div>
the validate method of actionform is always called when the form is submitted. you cannot manually call it unless you r reimplementing struts in ur own way. if u want a method to do the same work as the validate method, move the code of the validate method into another method and call it in the validate method. I do not completely understand what you are trying to do so please be more specific.

Categories

Resources