Struts form automatically submitted when using validate() method - java

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.

Related

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;
}
}

Attempting to make a delete button in Thymeleaf / Spring MVC

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})}"

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

Send data from database to jsp using javaservlet

this is my first time attempting this kind of application I have a jsp file
<html>
<head>
<title>Flight booking</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css" type="text/css"
media="screen">`enter code here`
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("fname")%> !
</title>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel body" id="inner_panel_1">
<h4>
Welcome ,
<%=session.getAttribute("fname")%></h4>
</div>
<!--end panel 1 -->
<div class="panel body" id="inner_panel_2">
<form action="CustomerServlet" method="post">
<label for="viewClientInfo">View/Change
Client Information</label>
<input type="submit" name="viewClientInfo" id="viewClientInfo" class="btn btn-success"
data-toggle="collapse" data-target="#clientPanel">
</form>
<!-- end panel body -->
<div id="clientPanel" class="collapse">
<div
class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xs-offset-0 col-sm-offset-0 col-md-offset-3 col-lg-offset-3 toppad">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title"></h3>
<td> <%=session.getAttribute("fname")%> </td>
<td> <%=session.getAttribute("lname")%> </td>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3 col-lg-3 " align="center">
<img alt="User Pic"
src="http://icons.iconarchive.com/icons/icons8/windows-8/128/Transport-Airplane-Takeoff-icon.png"
class="img-circle img-responsive">
</div>
<div class=" col-md-9 col-lg-9 ">
<table class="table table-user-information">
<tbody>
<tr>
<td>First Name :</td>
<td><%=session.getAttribute("firstname")%></td>
</tr>
<tr>
<td>Last Name :</td>
<td><%=session.getAttribute("lastname")%></td>
</tr>
<tr>
<td>Apt Number:</td>
<td><%=session.getAttribute("aptNumber")%></td>
</tr>
<tr>
<td>Address</td>
<td><%=session.getAttribute("streetNum")%> <%=session.getAttribute("streetName")%>
</td>
</tr>
<tr>
<td>City, Country</td>
<td><%=session.getAttribute("city")%>, <%=session.getAttribute("country")%>
</td>
</tr>
<tr>
<td>Email</td>
<td><%=session.getAttribute("userEmail")%></td>
</tr>
<tr>
<td>Phone Number</td>
<td><%=session.getAttribute("phoneNum")%><br></td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-success" id="changePayment" data-toggle="collapse" data-target="#payment-panel">Change Payment Information</button>
</div>
</div>
</div>
</div>
</div>
<!--end panel 2 -->
</div>
<div id="payment-panel" class="collapse">
<div class="col-xs-12 col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Payment Details
</h3>
</div>
<div class="panel-body">
<form role="form" class="creditCard" action="CreditCardServlet" method="addCreditCard">
<div class="form-group">
<label for="cardNumber">
CARD NUMBER</label>
<div class="input-group">
<input type="text" class="form-control" id="cardNumber" placeholder="Valid Card Number"
required autofocus />
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
</div>
</div>
<div class="row">
<div class="col-xs-7 col-md-7">
<div class="form-group">
<label for="expiry">
EXPIRY DATE</label>
<div class="col-xs-6 col-lg-6 pl-ziro">
<input type="text" class="form-control" id="expiry" placeholder="MM/YYYY" required />
</div>
</div>
</div>
<div class="col-xs-5 col-md-5 pull-right">
<div class="form-group">
<label for="cvv">
CV CODE</label>
<input type="password" class="form-control" id="cvv" placeholder="CV" required />
</div>
</div>
</div>
</form>
<div class="col-md-4 text-center">
<button type="button" class="btn btn-success" id="submitPaymentInfo" >Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end inner panel -->
<div class="panel body" id="inner_panel_3">
<button type="button" class="btn btn-success" id="viewBookings" data-toggle="collapse" data-target="#client-bookings-panel">View
Bookings</button>
</div>
<div id="client-bookings-panel" class="collapse">
<p>Client Bookings Dump for next Version</p>
</div>
<!--end panel 3 -->
<div class="panel body" id="inner_panel_4">
<button type="button" class="btn btn-success" id="bookFlightButton" data-toggle="collapse" data-target="#flight-booker-panel">Book
Flight for Next Version</button>
</div>
<div id="flight-booker-panel" class="collapse">Link to Flight Booker</div>
<!--end panel 4 -->
</div>
</div>
<!--end container -->
</body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
I am trying to get the information of the user that just logged in from the db and by using the jsp above display it to them
public class UserInfoServlet {
public void doGet(HttpServletRequest request , HttpServletResponse response)throws ServletException{
}
}
I know how to get information from jsp to java and save it to db but i do not know how to go to the oposite direction
You will need to connect to db then set the info in the session like this:
public class DatabaseAccess extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//you can use your own connection thing in you don't like the below code
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";
static final String USER = "root";
static final String PASS = "password";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
Statement stmt = conn.createStatement();
String sql;
sql = "YOUR QUERY. YOU SAID YOU ALREADY KNOW THIS";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()){
//Retrieve by column name
String fname = rs.getString("first");
String flast = rs.getString("last");
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
//get the session and set the values
HttpSession session = request.getSession();
session.setAttribute("fname", fname);
RequestDispatcher rd=req.getRequestDispatcher("/whateveristhejspname.jsp");
rd.forward(req, resp);
}
}
Make sure you have your mapping setup correctly in your web.xml file
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
public void doGet(HttpServletRequest request , HttpServletResponse response)throws ServletException {
HttpSession session = request.getSession();
//todo getSomeThing from DB
session.setAttribute("userInfo","yourMessage");
response.sendRedirect("your Page Location");
}
maybe you want this

java.lang.IllegalArgumentException: id to load is required for loading

This is my updateUser controller method
#RequestMapping(value = {"/edit-user-{id}"}, method = RequestMethod.POST)
public String updateUser(#Valid User userForm, BindingResult bindingResult, ModelMap model, #PathVariable Long id) {
model.addAttribute("edit", true);
model.addAttribute("success", "User " + userForm.getFirstName() + " " + userForm.getLastName() + " updated successfully");
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "forward:/registration";
}
userService.updateUser(userForm);
model.addAttribute("userForm", userForm);
return "registrationSuccess";
}
this one is my addDocuments method
#RequestMapping(value = {"/add-document-{id}"}, method = RequestMethod.GET)
public String addDocuments(#PathVariable Long id, ModelMap model) {
User user = userService.findById(id);
try {
if (user.getUsername() != null && !user.getUsername().equals(context.getUserPrincipal().getName())) {
return "login";
}
} catch (Exception ex) {
throw new DocumentNotFoundException("No document found with that id or userName");
}
model.addAttribute("user", user);
FileBucket fileModel = new FileBucket();
model.addAttribute("fileBucket", fileModel);
List<Catalog> documents = catalogService.findAllByUserId(id);
model.addAttribute("documents", documents);
return "manageDocuments";
}
when there is binding result error in updateUser method, it enters the "registration.jsp"
and at that time when I press add document button, it throws this kind of exception
nested exception is java.lang.IllegalArgumentException: id to load is required for loading.
this is registration jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="comment" content="">
<meta name="author" content="">
<title>Create an account</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="${contextPath}/resources/css/common.css" rel="stylesheet">
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
</head>
<body>
<div class="container">
<form id="logoutForm" method="POST" action="${contextPath}/logout">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
<form:form method="POST" modelAttribute="userForm" class="form-signin">
<c:choose>
<c:when test="${edit}">
<h2 class="form-signin-heading"><spring:message code= "account.edit.label"/></h2>
</c:when>
<c:otherwise>
<h2 class="form-signin-heading"><spring:message code= "account.create.label"/></h2>
</c:otherwise>
</c:choose>
<c:if test="${!edit}">
<spring:bind path="username">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="text" path="username" class="form-control" placeholder="Username"
autofocus="true"></form:input>
<form:errors path="username"></form:errors>
</div>
</spring:bind>
</c:if>
<spring:bind path="firstName">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="text" path="firstName" class="form-control" placeholder="First name"
autofocus="true"></form:input>
<form:errors path="firstName"></form:errors>
</div>
</spring:bind>
<spring:bind path="lastName">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="text" path="lastName" class="form-control" placeholder="Last name"
autofocus="true"></form:input>
<form:errors path="lastName"></form:errors>
</div>
</spring:bind>
<spring:bind path="email">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="text" path="email" class="form-control" placeholder="Email"
autofocus="true"></form:input>
<form:errors path="email"></form:errors>
</div>
</spring:bind>
<spring:bind path="skypeID">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="text" path="skypeID" class="form-control" placeholder="Skype ID"
autofocus="true"></form:input>
<form:errors path="skypeID"></form:errors>
</div>
</spring:bind>
<spring:bind path="password">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="password" path="password" class="form-control" placeholder="Password"></form:input>
<form:errors path="password"></form:errors>
</div>
</spring:bind>
<spring:bind path="passwordConfirm">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="password" path="passwordConfirm" class="form-control"
placeholder="Confirm your password"></form:input>
<form:errors path="passwordConfirm"></form:errors>
</div>
</spring:bind>
<c:if test="${edit}">
<span class="well pull-left">
<spring:message code= "button.upload.text"/>
</span>
</c:if>
<button class="btn btn-lg btn-primary btn-block" type="submit"><spring:message code= "button.submit.label"/></button>
<h3><a onclick="document.forms['logoutForm'].submit()"><spring:message code= "button.logout.label"/></a></h3>
</form:form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
</body>
</html>
please help me find out how to redirect or forward.

Categories

Resources