Simple navigation through pages spring - java

I am a Spring beginner and was recently looking at this tutorial
http://www.mkyong.com/spring-mvc/spring-mvc-form-handling-annotation-example/
(There's a download link at the bottom of the page and with a quick maven install you should be able to run the project very easily.)
I noticed that when I pressed the submit button on the 1st page and it goes to the 2nd page, the URL stays the same. Now, I modified the 2nd page to have its own form. Unfortunately, because the URL is still the same on the 2nd page, Spring picks the controller for the 1st page when I click the 2nd page's submit button.
Why does this happen and how can I override this behavior?
Apologies if I am not being clear enough. Feel free to ask for certain clarification.
Thanks for your time
Regards
Steve
EDIT : My 2nd page's form looks like this
<form:form method="POST" commandName="step2">
<table width="800" align="center"
style="border-width: 5px; border-style: solid; border-color: gray;">
<caption>
<b>STEP 2</b>
</caption>
<tr>
<td></td>
<td colspan="3"><input type="submit" value="Submit Page 2"
cssClass="field" /></td>
</tr>
</table>
</form:form>

If you want the url to be updated when you navigage from Page1 to Page2 with Page2 url. Then use redirect on the server side instead of forward. I'm not how you do in Spring MVC, you may want to check Spring MVC reference manual.

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?

GET method sent instead of DELETE

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.

Best Practice to refresh the data in JSP without refreshing the whole page

How is it possible to refresh the data which i get from the servlet in the jsp page without refreshing the whole page.
I am not satisfied with my solution now, which is:
polling a jsp page from the server and loading it in a div container. (See following)
My jsp file would look like following:
<c:forEach items="${list}" var="myList" >
<tr>
<td class="aligncenter">
<span class="center">
<input type="checkbox" name="option${myList.id}" value="${myList.id}"></input>
</span></td>
<td class="listId">${list.id}</td>
<td>${myList.title}</td>
<td>${myList.description}</td>
<td style="text-align:center;"><img style="height:40px;" src="../../app/images/food/thumbnail/${myList.imagePath}"></img></td>
</tr>
</c:forEach>
Know i have a method which calls a method in my controller that retrieves a this jsp file with the attributes in the model.
Then I load this jspfile in a div with jquery
jQuery('.myDivWhereIWantToLoadMyJspFile').load(data);
Is there a other possibility to refresh the data in a jsp page except websockets?
This is possible using an Ajax request, that is meant to be used for partial page refreshes. With ajax a request is sent to the server but the page remains the same.
Then an event is triggered when the response arrives. In response to that event we can modify parts of the page with fresh data without reloading it.
See this answer for an example of how to do it with jQuery.

How to modify include file in jsp page without showing blank content

I am a beginner with jsp servlets, and I need some help having my page not show up blank when I make changes. I am trying to include the the code from a donate-box.jsp into the layout of the org-about-panel.jsp page, which itself is included in another view jsp file. When I makes change to donate-box, then load the view file, I am seeing a blank site, and then upon refreshing, it shows up as before without the donate-box.
Here is the code I am trying to include, from the donate-box:
<logic:notEqual name="hideDonateBox" value="true">
<form action="https://<%=request.getServerName()%><%=contextPath%>/cartDonate.do method="get">
<input type="hidden" name="targetPage" value="<%=requestedPathWithQuery%>">
<div class="donateBox">
<logic:notEmpty name="detailOrgBean" property="offerings">
<table class="donateBox" cellpadding="0" cellspacing="0">
<logic:iterate name="detailOrgBean" property="relatedOfferings" id="receiver" indexId="oppIndex" length="5">
<tr class="donateBox">
<td class="donateBox">
<input type="radio" name="receiverId"
value="<bean:write name="receiver" property="id"/>">
</td>
<th class="donateBox" align="right">
$ -
/donate/<%= formatter.getUrlPath((Receiver) receiver) %>">
" CHECKED>
">
$ (Other)
This file is being included in another file with this code. I have tried commenting out the logic:notequal or logic:empty tags.
<%# include file="/templates/donate-box.jsp" %>
Thanks in advance!
This problems appears because your jsp (donate-box) can't be compiled (Such behavior I've seen in tomcat).
From quick look, I can say that requestedPathWithQuery - variable is undefined in scripting.
For more precise description you can take a look in logs

Categories