i have a html table:
<div id="connInfoMainDiv">
<table>
<tr>
<td>Connection</td>
<td>Action</td>
</tr>
<tr>
<td>On</td>
<td>
<input type"radio" checked="checked" value="0" name="rs[0].selection"> off
<input type"radio" checked="checked" value="1" name="rs[0].selection"> on
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="btnSubmit" text="submit" /></td>
</tr>
</table>
</div>
here is my java controller:
#RequestMapping(method=RequestMethod.GET, value="/conn/ajax")
public String getAjaxConnInfo(#ModelAttribute("ConnForm")ConnForm connForm,
BindingResult result,
ModelMap model,
final RedirectAttributes redirectAttributes) {
.....//get data from web service
model.addAttribute("connForm", connForm);
return "/conn/ajax";
}
here is my connForm:
public class ConnForm {
private List<connT> connList;
}
here is my connT class:
public class connT {
private int connStatus = 0; // 0=off, 1,on
private boolean radioSelected = false;
}
here is my ajax which does the polling:
$(document).read(function() {
setInterval(getConnInfo, 2000);
});
function getConnInfo() {
$.get("http://domain.com/conn/ajax", function(data) {
$("#connInfoMainDiv").html(data);
});
}
i implemented a ajax polling to constantly update the data on this page. what happen in the controller is it will get the data from database, set it to the object and return it to the jsp template. i previously asked here
here is the problem im encountering:
- Connection is off, radio button "off" is checked
- i clicked radio button "on".
- before i could click submit, the ajax kicks in. when this happen, it updates the page and the radio button "off" is checked.
how can i keep the radio button "on" checked??
Related
How do you send a value of a button to a Controller?
I have the following HTML
<form th:method="POST" th:action="#{'/bet/addGame/{gameId}'
(gameId = ${game.getGameId()})}">
<th scope="row"><button class="btn btn-primary" name="konTip" value="1" th:text="${game.getCoef1()}">1.15</button></th>
<th scope="row"><button class="btn btn-primary" name="konTip" value="X" th:text="${game.getCoefx()}">4.20</button></th>
<th scope="row"><button class="btn btn-primary" name="konTip" value="2" th:text="${game.getCoef2()}">3.40</button></th>
</form>
As you can see from the image I have three buttons under the "1, X and 2" row I want to pass the value of the button on which the user clicks to the Controller on the Back-end say like a RequestParam for example but I have no idea how to do this.
I tried to add JS to it but I can't really understand the thymeleaf documentation very well
This is my Controller Class
#PostMapping("/addGame/{gameId}")
public String addGameToTicket(#PathVariable Integer gameId, Model model, HttpServletRequest request) {
User user = (User) request.getSession().getAttribute("user");
Ticket ticket = this.ticketService.findTicketByUser(user.getUsername())
.orElseThrow(()->new TicketNotFoundUserNameException(user.getUsername()));
Game gameToAdd = this.gameService.findById(gameId);
this.ticketService.addGame(user.getUsername(), gameId);
return "redirect:/bet";
}
I am trying to create a table that displays a list of all logs that have been added. In addition to displaying the info I wanted to have another column of checkboxes that when clicked would allow me to delete them with the corresponding delete button.
The issue that I am having is that I am unable to put the values from my checkboxes into the array of Longs. I also want to keep the functionality of my table as it displays correctly.
For my table I have the following code:
<form method="post" th:action="#{/projects/log/delete/}" th:object="${deleteForm}">
<div th:each="log : ${allLogs}" class="row">
<tbody>
<tr class="active">
<td>
<input type="checkbox" th:field="*{logIds}" th:value="${log.id}" />
</td>
<td th:text="${log.teamUsed}"></td>
<td th:text="${log.opponentStarters}"></td>
<td th:text="${log.opponentOthers}"></td>
<td th:text="${log.myStarters}"></td>
<td th:text="${log.myOthers}"></td>
<td th:text="${log.result}"></td>
</tr>
</tbody>
</div>
<button type="submit" id="deleteButton" class="hidden"></button>
</form>
The form that I am trying to place the checkbox values into is: (log.id is a long)
public class LogDeleteForm {
private List<Long> logIds = new ArrayList<>();
public List<Long> getLogIds() {
return logIds;
}
public void setLogIds(List<Long> logIds) {
this.logIds = logIds;
}
}
In my controller I have the following setup for my view:
#RequestMapping(value = "pokemon_log", method = RequestMethod.GET)
public String view(Model model) {
model.addAttribute("addForm", new logForm());
model.addAttribute("deleteForm", new logDeleteForm());
model.addAttribute("allLogs", logService.getAllLogs());
return "log";
}
I am able to implement the deletion fine I am just unable to get the Ids that I would like to delete. How can I get the checkbox values placed into the list of longs?
Turns out that my issue was in my deleteLogs method:
#RequestMapping(value = "/log/delete", method = RequestMethod.POST, params = "delete")
public String deleteLogs(#ModelAttribute("deleteForm") logDeleteForm deleteForm) {
List<Long> formIds = deleteForm.getLogIds();
if (formIds == null || formIds.size() == 0) {
return "redirect:/projects/log";
}
for (Long id : formIds) {
logService.deleteLog(id);
}
return "redirect:/projects/log";
}
My redirects were both "redirect:/log" instead of "redirect:/projects/log"
Also my button was missing name="delete" because it was unable to qualify as a submit with a delete param.
I am trying to fire onClick event and Spring controller one by one.
In the click event of the button, I set a hidden field and then I want the controller to be executed AND the hidden field to be available in it. Here is my code for the JSP and the Spring Controller
JSP
<html:hidden property="MenuID" name="MenuID" id="hidMenuID" />
<c:forEach items="${menus}" var="menu" >
<tr class="cartItem">
<td align="left" >${MenuId}</td>
td align="right"><input type="text" name="menu_name" value="${Name}"/></td>
<td align="right"><input type="text" name="menu_price" value="${MenuPrice}"/></td>
<td align="right"><input type="submit" class="button" name="add_menu" value="Add" onclick="return SetMenuID();"></td>
<td align="right"><input type="submit" class="button" name="remove_menu" value="Remove" onclick="return SetMenuID();"></td>
</tr>
</c:forEach>
JavaScript
<script type="text/javascript">
function SetMenuID()
{
var MenuID = document.getElementById('hidMenuID');
MenuID.value = 'The new value';
return true;
}
</script>
Spring MVC
#RequestMapping(params = "add_menu", method = RequestMethod.POST)
public ModelAndView AddMyMenu(#RequestParam("MenuID") String menu_id, Model model, #ModelAttribute("cart") ArrayList<Menu> mycart)
{
int nMenuId = Integer.parseInt(menu_id);
Menu menu = m_arrMenus.get(nMenuId);
model.addAttribute("menus", GetMenus());
mycart.add(menu);
return new ModelAndView("edit_menu");
}
As you might guess, I am populating data from database. I have an onClick function associated with each ADD button. I set hidden field in thid function and want it to be available in my controller. But a runtime exception comes that
Error Status 400 - Required string MenuID is not present
What should I do to achieve similar result ? Thanks for any input.
#RequestParam expects a parameter my name in the request url.
Since your form is submitted and there are no request param that the action recieves. This is a reason you are getting 400 http error from server.
See the difference between #RequestParam vs #PathVariable
So either change the #RequestParam annotation or add (required = false) to it.
I have got a html page (with Thymeleaf):
<form action="#" th:action="#{/changeme}">
<fieldset>
<table style="width: 500px">
<tr th:each="esfield : ${esfields}">
<td>
<div>
<div class="checkbox">
<input type="checkbox" name="optionsMulti"
th:text="${esfield}" />
</div>
</div>
</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>
<button type="submit"
class="btn btn-xs btn-primary margin10-right paddingNew"
name="save">Calculate!</button>
</td>
<td></td>
</tr>
</table>
</fieldset>
</form>
When I click Calculate! it goes to my controller
#RequestMapping(value = "/changeme", params = { "save" })
public String save(final ModelMap m) {
m.addAttribute("centers", /*params*/);
return "clustering";
}
I would like to get information about checked boxes in my controller?
How can I do that?
Thank you in advance
You have basically two options :
either you use a different name for each checkbox
or you use spring tag <form:checkbox> instead of native <checkbox>
If you don't posted data will not allow you to know exactly what boxes were actually checked (excepted in cases all and none)
With the approach, you should use in your controller a #ModelAttribute annotated object containing a List<Boolean> and spring will automagically populate it with the values of your checkboxes.
#RequestMapping(value = "/changeme", params = { "save" })
public String save(#ModelAttribute BoxesForm form, final ModelMap m) {
// do what you need with form.getCheckboxes() ...
m.addAttribute("centers", /*params*/);
return "clustering";
}
public class BoxesForm {
List<Boolean> checkboxes;
// getter and setter omitted ...
}
Hi I have a JSP page as below,jsp page contains one table in which i am displaying data by iterating through the list from the action class.
each row of a table has refresh button at row level.jsp is as shown below.
<script type="text/javascript">
function refreshRecord(id)
{
$(document).ready(function(){
var fileId=id;
alert(fileId);
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data: {fileId:fileId},
success:function(data){
alert("returned from action");
}
});
});
}
</script>
</head>
<body>
<%#include file="index1.html" %>
<div class="box2">
<div class="box3">
<s:property value="userId"/>
</div>
<center><h2>FILE STATUS</h2></center>
<center>
<form action="Upload" method="post" enctype="multipart/form-data">
<label for="myFile" class="text">Upload your file:</label>
<input type="hidden" name="upload" value="upload"/>
<input type="file" name="myFile" size="40" class="file"/>
<input type="submit" value="Upload" class="button"/>
<input type="submit" value="Refresh" class="button"/>
</form>
</center>
<center>
<table border="1" class="displaytab" id="rtable">
<s:if test="%{user.roles == 'admin'}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;"><center>Admin</center></td></tr>
</s:if>
<tr>
<th>FileId</th><th>File Name</th><th>Upload Date</th><th>#Records</th><th>Status</th><th>Estimated Time</th><th>Processed Records</th><th>Generate Report</th><th></th><s:if test="%{user.roles == 'admin'}"><th>Controls</th></s:if>
</tr>
<s:iterator value="uploadList" var="m">
<tr>
<td><s:property value="%{#m.fileId}" /></td>
<td><s:property value="%{#m.fileName}" /></td>
<td><s:property value="%{#m.uploadDate}" /></td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><s:property value="%{#m.status}" /></td>
<td>tbd</td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><img src="images/generate.png" title="Generate Report"> </td>
<td><img src="images/refresh.png" title="Refresh" onclick="refreshRecord(<s:property value="%{#m.fileId}" />);"></td>
</tr>
</s:iterator>
</table>
</center>
at the refresh button onclick i am calling onclick="refreshRecord();"> this javascript method it will go to action class get the latest values of status and # records.
through ajax i am passing this fileId to action class checkStatusAndNumRecsAction.java to get the updated status and #records column values from database
my action class is as below
import com.mxui.db.api.PersistenceService;
import com.mxui.db.service.*;
import com.opensymphony.xwork2.ActionSupport;
public class checkStatusAndNumRecsAction extends ActionSupport
{
/**
*
*/
private static final long serialVersionUID = 6450400234448854648L;
private String status;
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
private long numRecords;
public long getNumRecords()
{
return numRecords;
}
public void setNumRecords(long numRecords)
{
this.numRecords= numRecords;
}
private String fileId;
public String getFileId()
{
return fileId;
}
public void setFileId(String fileId)
{
this.fileId = fileId;
}
public String execute()
{
PersistenceService svc = PersistenceServiceImpl.getInstance();
status = svc.getStatusByFileId(fileId);
System.out.println("status is "+status);
numRecords = svc.getNumRecordsByFileId(fileId);
System.out.println("num records are "+numRecords);
return "SUCCESS";
}
}
this action get the values of status and #records from database
what i want to do is i should get the values of status and numRecords from action class to jsp using ajax and replace the tables of status and #records column with the new retrieved data from action class.on click of that row refresh button.
In the function defined in success: you will need to write javascript that replaces the contents of the <TD> for the record that has been refreshed. You can identify the <TD> by using the fileId. For example: <td id="%{#m.fileId}"><s:property value="%{#m.status}" /></td> and using jQuery search for this fileId and by using replaceWith substitute the new value of status. For example: $("td#fileId").replaceWith(newStatusData);
Depending of the format of the data returned to the AJAX call you might need to do some parsing in order to extract the data that you want.
EDIT: Just seen your comment. Can you control to format of the data returned to the AJAX call? If so you might like to format in JSON. Although a simple CSV format would be sufficient. Also can you post an example of the data sent back to the AJAX.
You appear to be missing a servlet that recuperates the values from the DB and sends then to the client. In your servlets doPost() method you need to call the methods that return the status of the record and number of records and return them to the client. I imagine servlet code something like this:
#WebServlet(checkStatusAndNumRecs)
class MyServlet extends HttpServlet
protected doPost(HttpServletRequest request, HttpServletResponse)
throws IOException, ServletException{
String fileId = request.getParameter("fileId");
String status = XXXXX.getStatus(fileId);
String numRec = XXXXX.getNumRecords();
String responseTxt = status + "," + numRec;
response.out.println(responseTxt);
response.getWriter().println(responseTxt);
}
XXXXX is the object that encapsulates the calls to the DB to retrieve the values of status and record number.
And also you need to change to jQuery AJAX to something like this:
$.ajax({
type: "post",
url: "checkStatusAndNumRecs",
data: "fileId=" + fileId,
success: function(data){
var rData = data.split(",");
$("td#fileId").replaceWith(rData[0]);
// Do the same for the record number data: rData[1]
}