GET method sent instead of DELETE - java

I am trying to write the frontend of an application, and I've run into a problem. I've been trying to realize a DELETE method using AJAX, but according to Spring a GET is sent when I run the code.
HTML code:
<tr th:each="attraction : ${attractions}" th:object="${attraction}">
<td th:text="*{name}"></td>
<td th:text="*{latitude}"></td>
<td th:text="*{city}"></td>
<td><a th:href="|/edit/*{id}|">EDIT</a></td>
<script>
function sendDelete(event) {
xhttp.preventDefault();
xhttp.open("DELETE", this.href);
xhttp.send();
}
</script>
<td><a th:href="|/delete/*{id}|" onclick="sendDelete(event);">DELETE</a></td>
</tr>
Spring code:
#DeleteMapping("/delete/{id}")
String delete(#ModelAttribute Attraction attraction) {
attractionService.delete(attraction);
return "redirect:/";
}
How could I solve this problem? Thank you in advance.

You went the long way around to fix this.
Link tags can send whatever http method you wish, as long as you are handling it in JavaScript and you call preventDefault.
But you have to do it on the event passed into the click handler not on the xhttp pbject. So on your event handler you should have done
event.preventDefault()
and not:
xhttp.preventDefault()
Your form hack isn't idiomatic. It'll freak out the next person who works on that code!

With some help, I could figure out the problem. The basic problem is that the
< a > tag is only able to handle GET methods.
Instead that part of my code, I sorted it out like this in HTML:
<td>
<form th:method="DELETE" th:action="|/delete/*{id}|">
<input type="submit" value="Send">
</form>
</td>
Now it works perfectly.

Related

Why does this Spring Boot/Thymeleaf button hide my data or not work at all?

I'm curently trying to get into Spring Boot and Thymeleaf by following tutorials and playing around with the code they provide. I tried implementing an extra functionality and had the following problem: The code should display a ToDo-List consisting of ToDo-Objects that each have a name, description and a boolean status that denotes if they are done or not. Each line of the table is supposed to have a button to click in order to mark a ToDo as done.
<table style="border-collapse:collapse; font-family: Arial,Arial,sans-serif;">
<tr>
<th padding: 5px"></th>
<th> To-Do</th>
<th> Description</th>
<th> Done?</th>
</tr>
<tr th:each="todo : ${todos}">
<td>
<!-- <form method="POST" th:action="#{/updateDone(exactToDo=${todo})}">
<button type="submit" name="submit" value="value" class="link-button">Done</button>
</form> -->
<form method="POST" th:action="#{/updateDone}">
<input type="hidden" name="exactToDo" id="exactToDo" th:value="${todo.getName()}" />
<button type="submit" name="submit" value="value" class="link-button" >This is a link that sends a POST request</button>
</form>
</td>
<td th:utext="${todo.name}" style="border: 1px solid black;">...</td>
<td th:utext="${todo.description}" style="border: 1px solid black;">...</td>
<td th:text="${todo.done} ? 'Yes! ' : 'No' " style="border: 1px solid black;">...</td>
</tr>
</table>
Displaying the contents works, but my button does nothing in this configuration. I followed the directions from this older question, but it doesn't change the status of my ToDos. I can see in the Browser console that it sends a Post request, but there seems to be nothing inside.
The part that is currently commented out makes the data disappear from my table, only leaving the first line with the headers. I tried various similar approaches that I found online, but they all had one of those two results.
Here is the code of the relevant controller:
#RequestMapping(value = {"/updateDone"}, method=RequestMethod.POST)
public String completeTask(Model model, #RequestParam("exactToDo") String exactToDo){
for (ToDo todo : todos){
if (todo.getName().equals(exactToDo)){
todo.markDone();
}
}
return "list";
}
Setting return to "redirect:/list" fixes the problem with the "disappearing" data, but the status of the ToDo still doesn't change. I assume that the problem is that the ToDo object isn't sent to the method correctly, but I'm not exactly sure why. You might have noticed that I am trying to send todo.getName() instead of the ToDo Object directly, that is because when I try to send the object, I get an error in the second line of my posted Controller code, telling me that a String couldn't be converted into a ToDo-Object (the Controller was of course configured to take a ToDo object as parameter). This is why I think the problem has to be somewhere there.
I'd be very grateful if someone could help me fix this problem or point me to a better way of having a button on an HTML-page activate a method in my Java-Code. Tips for good learning resources are also greatly appreciated. I'm trying to learn Spring and Thymeleaf in order to make User Interfaces for Java programs.
Thank you for your time!
First thing First.
Why would you need to write so much (form) just for a button? Now if you "must" use form then you are missing the th:object="${todo}" in your form tag. It will help Controller to understand on what object you are going to take some action.
But I would suggest you use this inside your 'td' block instead of a form. It will do the same job for you. Once your request is successful, you can redirect it to your list and you should see the new results getting reflected immediately.
Mark Done
You can refer this to see a full blown example. Here you will find two things. User Controller and Task Controller that might interest you.
For anyone who might find this later, here is the answer:
The link Ajay Kumar posted ended up working, with a little tweak to include the necessary parameter:
<a href="/updateDone" th:href="#{/updateDone(exactToDo=${todo.getName()})}" >Mark Done</a>

How to submit a form using Java HttpURLConnection when button is image

I am trying to write a program in Java using only the java.net.* libraries (i.e. HttpURLConnection, URL...) - this is a requirement for this project (i.e. no external packages like HttpClient, JSoup, etc...). The ultimate form submission 'Go button' is actually a picture that the user clicks. It's code snippet is here:
<script>
var form = $('pdb');
function proceed() {
form.submit();
}
</script>
<div id=input_nav>
<table class="nav_entry" onclick="proceed();" align=right>
<tr>
<td align="right">Next Step:<br/>Select Model/Chain</td>
<td align="right">Next Step:<br/>Select Model/Chain</td>
<td width="51" align="left"><img src="images/basic/next.png"></td>
</tr>
</table>
</div>
To my understanding, form submission using Java's .net library requires sending the HTML' code's gui object name-value pairs, but as can be seen from the HTML source code snippet, no such fields exist foe the button. Could someone please give me some direction with how this job can be accomplished?

Thymeleaf .html passing parameter to MVC Spring Controller Java

im new to thymeleaf and Spring - im doing some small project to my school class and i have a problem with html link. I had troubles with it for 2hours now and im editing my code in 10 diffrent ways so please answer how to do it properly. Below its my html template (i tried using here th:href with two diffrent ways:
<table>
<th>Name</th>
<th>Date</th>
<th>See</th>
<th>Edit</th>
<a th:each=" i : ${workouts}" varStatus="status">
<tr>
<td><a th:text="${i.getName()}"/></td>
<td><a th:text="${i.getDate()}"/></td>
<td>See</td>
<td>See</td> </tr>
</a>
</table>
And here its my Controller:
#Controller
public class SeeWorkoutController {
#RequestMapping(value = "/seeWorkoutPage/{id}", method=RequestMethod.GET, params="id")
public String test2(#PathVariable("id")Long id, Model model) {
System.out.println(id);
return "workoutsPage";
}
but it's now working properly. Please help.
Check the documentation for Thymeleaf Link URLs. In particular this example:
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
view
I think you're almost there with your second example, but it should read
th:href="#{/seeWorkoutPage/{workoutId}(workoutId=${i.getId()})}"
Note how you specify the {workoutId} parameter, then give it's value between the brackets afterwards.
Try:
<span th:each="workout: ${workouts}">
<td><a th:text="${workout.name}"/></td>
<td><a th:text="${#dates.format(workout.date,'MMM d, yyyy')}</td>
<!-- add other stuff when you have the above working -->
</span>
You don't need the get() syntax (and it can throw an exception in some containers). Also, it looks like you're nesting anchor (<a>) tags too.

Why is my post not give data to my controller from my form?

I am developing a Sprin MVC application and I have a form containing a table in one of the UI jsp's, (welcome.jsp) and when the submit button is clicked, I am trying to print out the data in the form to the web applications console.From there i intend to parse the checkboxes that are selected and then have the controller send the 'selected' data back to the databased to be updated to the next status in the applications flow.
So far the form is 'successfully' posting as in no error or exceptions is being thrown, but the printed statement in the console is blank which makes me think that no data is being sent, and I would greatly welcome any help to fix this.
Here is the setup of what I have, not the actual code but a rough set up of the elements and methods.
welcome.jsp:
<form action="<c:url value="/postPage" />"method="post" modelAttribute="rTable">
<br/>
<table>
<thead>
<tr>
<th>title1</th>
<th>title2</th>
<th>title3</th>
<th><select>
<option>option1</option>
<option>option2</option>
</select></th>
</tr>
</thead>
<tbody>
<tr>
<td>value1</td>
<td>value1</td>
<td>value1</td>
<td><input type="checkbox" value="row_data_id" /></td>
</tr>
</tbody>
<tfoot>
<tr><td colspan="4"></td>
</tfoot>
</table>
<br/>
</form>
My controller has the following method in it with all the necessary libraries imported:
controller.java
#RequestMapping(value="/postPage", method = RequestMethod.POST)
public String processUpdate(#ModelAttribute("rTable") String table, ModelMap model) {
System.out.println(table);
return "postPage";
}
The console line that is print is this:
.
.
.
[3/19/14 16:36:53:625 EDT] 0000006a SystemOut O
.
.
.
Does anyone know why this is not printing anything? Am I really not successfully sending anything to the controller?
After a good deal of reading and trial and error I found my answer. I will explain in terms with spring framework forms. In order to pass data through the form from front-end to back end, first every input will need to be tied to the form using the spring form JSTL tag
ex.
form => form:form
input=> form:input
in the form:form it isn;t necessary but you should have a modelAttribute that is linked to a java class, then in each input their need to be a path attribute the is linked to a variable in the modelAttribute class and a value to assign to the variable. Then on a submit the values are linked to the back end via the getters and setters on the java class to be used in the back-end. I hope I am explained that clearly.

JSP forms with Spring mvc

I create the following JSP.This jsp creates two buttons.
<form:form method="POST" action="${pageContext.request.contextPath}/link">
<div class="button-container" style="float:left;clear:right">
<table>
<tr>
<td>
<input id="post" type="image" src="${pageContext.request.contextPath}/<spring:theme code="image"/>votup.png"
</td>
</tr>
<tr class="hidden">
<td class="hidden">
<input type="text" name="mark" value="up"/>
</td>
</tr>
<tr>
<td>
<input id="post" type="image" src="${pageContext.request.contextPath}/<spring:theme code="image"/>votdown.png"
</td>
</tr>
<tr class="hidden">
<td class="hidden">
<input type="text" name="mark" value="down"/>
</td>
</tr>
In the controller class
#RequestMapping(value = "/link", method = RequestMethod.POST)
public String sendMark(#RequestParam("mark") final String marking){
}
I notice that the value of the String marking= up,down.This happens no matter which of the 2 buttons i click. Instead of this i want to be only up or down according to the button that the user will click.(If click at the first button should be up, if click at the second button should be down). I understood that the reason i take this result is because i named both of the hidden values as mark, but i don't know how to make the seperation with another way. Actually is the first time i'm doing something with JSP.Could i use some tag libraries for this problem?Any comments or answers are much appreciated!
Thank you
I'll advise you to put only one hidden field and change its value with javascript before processing the POST command.
I recommend you to create two separate forms for the two buttons and both form will contain the hidden field. Now you will get only one value.
But if you create two separate forms with different actions then you won't need the hidden field.
Hope this helps you.
Cheers.
As i understand, you will submit the form eithef for vote up or down. And you want 2 buttons for each action in the same form, but don't know how to make the difference. I would do something like this:
On form, put the action according to your request mapping (seems already done).
Then, both buttons would be made to submit the form. First of all, both your buttons have the same id, and the id has to be unique for each element. So, give your arrows and form id's like:
<input id="postup" type="image"
<input id="postdown" type="image"
<form id="myform"
Then, pun an onclick action on it like:
And create 2 JS functions:
function postUp () {
$('#mark').val("up");
$('#myform').submit();
}
function postDown () {
$('#mark').val("down");
$('#myform').submit();
}
Your controller will look like:
#RequestMapping(value = "/link", method = RequestMethod.POST)
public String sendMark(Model model, HttpServletRequest request){
String mark = request.getParameter("mark");
return "yourjsp"
}
And you will have your value.
Hope it helps !
Regards !

Categories