I want to reference an index in a URL,
for the controller shown below,
such that when the button for first item in the list is clicked,
the corresponding URL to be called is:
/product/detailpage/index/0 ->for the first item
/product/detailpage/index/2 ->for the third item
and so on
How do I modify the code and the <form in code_1 section to satisfy these requirements?
HTML:
<tbody>
<tr th:each="product, iter : ${list}">
<td th:text="*{product.id}"></td>
<td th:text="*{product.name}"></td>
<td style="text-align: right;">
<form action="#{/product/detailpage/index/(idx=${iter.index})}">
<input type="submit" value="Details" />
</form>
</td>
</tr>
</tbody>
Java:
#Controller
#RequestMapping("/product/detailpage")
public class ProductDetailPageController
{
/**
* It is the developer's responsibility to provide code that handles
* the concatenation the correct index to this AttributeName,
* so as to get the the corresponding value from the Model data structure.
* For example, productDetailAtIndex_0,
* productDetailAtIndex_1,
* productDetailAtIndex_n
*/
public static final String sProductDetailPageAttrName = "productDetailAtIndex_";
#Autowired
private ProductService productService;
/**
* Solution-1
*/
#RequestMapping(value = "/index/{idx}", method = RequestMethod.GET)
#ResponseBody
You want to see /product/detailpage/index/0 instead of /product/detailpage/index/?idx=0? You just need to add a placeholder that matches your chosen variable name. Like this:
th:action="#{/product/detailpage/index/{idx}(idx=${iter.index})}"
or for a url
th:url="#{/product/detailpage/index/{idx}(idx=${iter.index})}"
Related
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.
Any help would be greatly appreciated:
In my JSP I have a dynamic list of questions with an input field for each question as such:
<logic:iterate name="listOfQuestions" id="listOfQuestionsId" indexId="indexId">
<tr>
<td align="right" width="100%"><bean:message key='<%= "prompt.question" + (indexId.intValue() +1)%>'/>: </td><td width="100%" nowrap="nowrap"><bean:write name="listOfQuestionsId"/></td>
</tr>
<tr align="center">
<td align="right" width="50%"><bean:message key="prompt.answer"/>: </td>
<td align="left" width="50%"><html:password property="questions" size="30" maxlength="40" indexed="true"></html:password></td>
</tr>
</logic:iterate>
The questions and answer fields are being displayed fine.
My only problem, is trying to access the value of the all the input fields in my action class.
Here is my form: MultipleQuestionsForm
public class MultipleQuestionsForm extends ActionForm {
private List<String> questions=null;
/**
* #return the questions
*/
public List<String> getQuestions() {
return questions;
}
/**
* #param questions the questions to set
*/
public void setQuestions(List<String> questions) {
this.questions = questions;
}
//omitted the rest (Validate, constructor, reset method)
}
Here is part of my ActionClass:
getQuestions() returns null
//Use the ValidateInfoForm to get the request parameters
MultipleQuestionsForm validateQuestionsForm = (MultipleQuestionsForm) form;
List<String> listOfquestions = validateQuestionsForm.getQuestions();
for(String s: listOfquestions) System.out.println(s); //nullPointer since getQuestions() doesn't return the input values
How do you expect your questions property should render as List<String> questions from your jsp/view? Have you tried debug your validateQuestionsForm? if so please check your questions property. All you need to do is change your list property into String array. Like this in your MultipleQuestionsForm,
private String[] questions;
And getter setter for this property. Now you can receive as string array and iterate it. Hope this helps.
I am trying to write freemarker template but could not able to parse with my object class.
My POJO is
public class Metrix {
#Id
String _id;
String loginId;
Date date;
List<MatrixDetail> headers;
//All getters and setters
}
public class MatrixDetail {
String header;
int time;
String detail;
//All getters and setters
}
//Controller after saving form
#RequestMapping(value = "/matrix/save", method = RequestMethod.POST)
public View saveMatrix(#ModelAttribute Metrix matrix, ModelMap model) {
System.out.println("Reachecd in matrix save" );
return new RedirectView("/TrackerApplication/header.html");
}
FTL template form part
<form name="matrix" action="matrix/save.html" method="post">
<table class="datatable" align:"center">
<tr>
<th>Login Id:</th> <th> <input type="text" name="loginId" value= ${matrixList.loginId} required /> </th>
</tr>
<tr> <td></td><td></td><td></td></tr>
<tr>
<th>Header</th> <th>Time</th> <th>Details</th>
</tr>
**// I am not getting how this nested object which is of type List<MatrixDetail>
// will get parse in my form.**
<#list matrixList.headers as header>
<spring:bind path = "MatrixDetail">
<tr>
<td> <input name = "header" value = ${header.header} /> </td>
<td> <input name = "time" value = ${header.time} /> </td>
<td> <input name = "detail" value = ${header.detail} /></td></tr>
</#list>
</table>
<input type="submit" value="Save" />
</form>
How can we write freemarker template for form processing of such kind of nested object?
I am getting issues in form submission.
I would strongly advise against this.
Forms might be displayable in email in some cases, but they may not always work in the email client, not to mention those that only ever read emails in text-only form won't be able to use them whatsoever.
If you need users to enter a form, link to a page on your site and have the form there instead.
I'm using Apache Struts 1.3 to render a grid, whitch is a html form embebed in a .jsp. Something like
<html:form action="/MyController.do?action=processForm">
<html:text property="taxation[0][0]" value="" styleClass="gridInputs"></html:text>
<html:text property="taxation[0][1]" value="" styleClass="gridInputs"></html:text>
...
<html:text property="taxation[10][10]" value="" styleClass="gridInputs"></html:text>
MyController is associated to an ActionForm:
public class MyForm extends ActionForm{
protected String taxation[][]= new String [10][10];
public String[] getTaxation() {
return taxation;
}
public void setTaxation(String[][] taxation) {
this.taxation = taxation;
}
The problem arise when I try to retrieve the information submitted by the form. Whithin MyController.class I've a simple dispatcher action
public class MyController extends DispatchAction {
public ActionForward processForm(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
MyForm myform = (MyForm) form;
// Here i can use the getter method to retrieve an array, but
// myform is already wrong populated from struts
}
return mapping.findForward("stage2");
}
I know I can use a Vector (unidimensional array) and It works just fine, but regrettably I need to follow some specs (and the specs force me to use the class MyForm with a 10x10 matrix...). How would be the right way to populated a two dimensional array using struts?
Thank you for the help!
Struts does not support filling of multidimensional array in Form bean. However, it does handle uni-dimensional array of an object. So as a work around if you can create a class (say MatrixRow) which itself contains an Uni-dimensional array and then you can create an Uni-dimensional array of that object in the form bean. Your new class will be look like
public class MatrixRow {
private String matrixCol[] = new String[10];
/**
* #return the matrixCol
*/
public String[] getMatrixCol() {
return matrixCol;
}
/**
* #param matrixCol the matrixCol to set
*/
public void setMatrixCol(String[] matrixCol) {
this.matrixCol = matrixCol;
}
}
Then in your form bean
private MatrixRow[] arrMatrix = new MatrixRow[10];
/**
* #return the arrMatrix
*/
public MatrixRow[] getArrMatrix() {
return arrMatrix;
}
/**
* #param arrMatrix the arrMatrix to set
*/
public void setArrMatrix(MatrixRow[] arrMatrix) {
this.arrMatrix = arrMatrix;
}
and In your JSP, you can use it something like
<html:form action="biArrayTestAction.do">
<table cellpadding="0" cellspacing="0" width="100%">
<logic:iterate id="matrixRows" name="biArrayTestForm"
property="arrMatrix" indexId="sno"
type="logic.MatrixRow" >
<tr>
<td><bean:write name="sno"/></td>
<logic:iterate id="matrixCol" name="matrixRows" property="matrixCol" indexId = "colNo">
<td>
<input type="text" name="arrMatrix[<%=sno %>].matrixCol[<%=colNo %>]">
</td>
</logic:iterate>
</tr>
</logic:iterate>
<tr>
<td align="center" valign="top" colspan="2">
</td>
</tr>
<tr>
<td align="center" valign="top" colspan="2">
<html:submit property="command" value="Test"></html:submit>
</td>
</tr>
</table>
When you submit that form you will get all columns of MatrixRow object filled with the values.
I hope this will help you. I don't find any other way of using multidimensional array in Struts1.
I have been hitting a brick wall with this problem for some time and no amount of searching and reading has turned up an answer. I have posted on the Spring forums, but to no avail. Maybe someone here can help?
I have a bean containing a HashMap which I have bound to form using the Spring:form taglib and Spring:bind. Binding to the view works perfectly, but upon submitting the form and handling with an annotation based controller the binding does not appear to work correctly. I get no exceptions, but the HashMap is not populated. Here is my setup:
The JSP:
<form:form method="post" action="updateUserPermissions" modelAttribute="wsPermissions" >
<table>
<tr class="head">
<td>Workspace</td>
<td>Read?</td>
<td>Write?</td>
<td>Manage?</td>
</tr>
<c:forEach var="ws" varStatus="wsItem" items="${selectedUserWSs}">
<c:set var="wsURI" value="'${ws.uri}'"/>
<tr>
<td>${ws.kbInfo.name} # ${ws.community.name}</td>
<td>
<spring:bind path="wsPermissions.map[${ws.uri}].read">
<input type="checkbox" <c:if test="${status.value}">checked</c:if> disabled="disabled"/>
</spring:bind>
</td>
<td>
<spring:bind path="wsPermissions.map[${ws.uri}].write">
<input type="checkbox" <c:if test="${status.value}">checked</c:if>/>
</spring:bind>
</td>
<td>
<spring:bind path="wsPermissions.map[${ws.uri}].manage">
<input type="checkbox" <c:if test="${status.value}">checked</c:if>/>
</spring:bind>
</td>
<td>[Remove]</td>
</tr>
</c:forEach>
</table>
<input type="hidden" name="userid" value="${selectedUser.email}" />
<input type="submit" value="Update user permissions" />
</form:form>
This displays fine, binding works, the checkboxes show the correct initial values. Form submission is then handled by this controller method:
#RequestMapping
public String updateUserPermissions(#ModelAttribute(value="wsPermissions") WorkspacePermissionMap wsPermissions,
#RequestParam String userid,
HttpServletRequest request, ModelMap modelMap){
// code to update permissions here.....
LOG.debug(wsPermissions.getMap().size());
//the above prints zero
return "redirect:editUser?id="+userid;
}
Debugging the controller method shows that HashMap is empty.
Here is the code for WorkspacePermissionMap:
public class WorkspacePermissionMap {
private Map<String, WorkspacePermission> map = new HashMap<String, WorkspacePermission>();
/**
* #param map the map to set
*/
public void setMap(Map<String, WorkspacePermission> map) {
this.map = map;
}
/**
* #return the map
*/
public Map<String, WorkspacePermission> getMap() {
return map;
}
}
and for WorkspacePermission:
public class WorkspacePermission {
private boolean read = false;
private boolean write = false;
private boolean manage = false;
/**
* #return the write
*/
public boolean isWrite() {
return write;
}
/**
* #param write the write to set
*/
public void setWrite(boolean write) {
this.write = write;
if (write){
setRead(write);
} else {
setManage(write);
}
}
/**
* #return the moderate
*/
public boolean isManage() {
return manage;
}
/**
* #param moderate the moderate to set
*/
public void setManage(boolean moderate) {
this.manage = moderate;
if (moderate){
setWrite(moderate);
setRead(moderate);
}
}
/**
* #param read the read to set
*/
public void setRead(boolean read) {
this.read = read;
if (!read){
setWrite(read);
setManage(read);
}
}
/**
* #return the read
*/
public boolean isRead() {
return read;
}
}
Can anybody please point out where I'm going wrong? Am I barking up completely the wrong tree, or have I made a stupid error?
Thank you for your help,
Chris
There's definitely some weirdness on the jsp path expressions needed for this.
I'm using hard coded values:
applicationDetails['first_name']
or for your example:
wsPermissions.map['hardcodeduri'].read
These work fine for me.
My advice is to try it first hardcoded and then see if you can alter this to use the dynamic variable.
How is that your HTML checkbox element has no name or value attribute on it? Spring isn't supposed to do 'all' the magic for you ;)