define html checkbox in struts 1.3 - struts-1

hi i try to build crud with struts 1.3
this my page jsp
<logic:notEmpty name="Listprojects">
<logic:iterate id="remonter" indexId="i" name="Listprojects" type="entitiesMysql.Remonter" >
<tr>
<td>
<%--<bean:define id="leadId" name="lead" property="id" />--%>
<html:checkbox property="projectsIds" value="<%=Listprojects.getId().toString()%>" styleId="<%=i.toString()%>" />
</td>
<td><bean:write name="remonter" property="id" /></td>
<td><bean:write name="remonter" property="name" /></td>
</tr>
</logic:iterate>
</logic:notEmpty>
my problem is in class jsp i cant define checkbox:
ERROR

my solution is :
add this code in your jsp page:
<div class="center">
<tr> <th><input type="checkbox" value="1" name="CR" id="remontercr" onclick="selectAllCR(this);" tabindex="8"/> <b>Remonter de C.P au C.R</b></th>
<th><input type="checkbox" name="PROD" value="2" id="remonterprod" onclick="selectAll(this);" tabindex="8"/> <b>Remonter de C.R au PROD</b></th></tr> </div>
to recover value of checkbox
public class GestionremonterAction extends Action {
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, InterruptedException {
/* code......*/
String decisioncocherCR=request.getParameter("PROD");
}

Related

Extra character(,) is added while using Textbox in spring

I am new to JSP and Spring. I want to insert a userID(U0005) using textbox in spring form but it is storing(,U0005). From where the "," is inserted?
The code I have written is:
/* In Register.jsp: */
<c:url var="addAction" value="/libUsr/add"></c:url>
<form:form action="${addAction}" commandName="libUsr">
<table>
<tr>
<td>
<form:label path="id">
<spring:message text="ID" />
</form:label>
</td>
<td><form:input path="id" required="true" /></td>
</tr>
</table>
</form:form>
/*
In UserController.java:
*/
#RequestMapping(value= "/libUsr/add", method = RequestMethod.POST)
public String addLibUsr(#ModelAttribute("libUsr") LibUsr libUsr){
libUsrDAO.saveOrUpdate(libUsr);
return "redirect:/register";
}
/*
In DAOImpl:
Saving the data through DAOs
*/
#Transactional
public void saveOrUpdate(LibUsr libusr) {
sessionFactory.getCurrentSession().saveOrUpdate(libusr);
}
Your problem is with this tag:
<form:label path="id">
As you are adding the attribute path to one label, which wont store any value, spring try to get the value and returns empty,yourID.
Change the path attribute of your label to:
<form:label for="id">
<spring:message text="ID" />
</form:label>
If you want to show the value of the id into that label use:
<label>${yourObject.id}</label>
or
<label th:value="${yourObject.id}"></label>
Path attribute is just for input, select, checkbox...not static values as label, span...

Table row data submit in struts 1.2

I have a table with each rows contain checkbox (Like gmail inbox). I want to select few checkboxes and submit data in one go to action class.
Please let me know how can i submit form using checkboxes.
First of all you must ensure that your form bean and your form action class are already working otherwise even if you prepare your jsp file you will not be able to check its correctness (Struts 1.2 drawback)
Here goes your jsp code
<%# taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<html:html>
<html:form action="/formAction" method="GET">
<table>
<tr>
<td>Data 1</td>
<td>
<html:checkbox property="chk" value="value1"></html:checkbox>dln</td>
</tr>
<tr>
<td>Data 2</td>
<td>
<html:checkbox property="chk" value="value2"></html:checkbox>dln</td>
</tr>
<tr>
<td>Data 3</td>
<td>
<html:checkbox property="chk" value="value3"></html:checkbox>dln</td>
</tr>
<tr>
<td>Data 4</td>
<td>
<html:checkbox property="chk" value="value4"></html:checkbox>dln</td>
</tr>
<tr>
<td>
<html:submit value="Register"></html:submit>
</td>
</tr>
</table>
</html:form>
Form Bean
public class MyFormBean extends ActionForm {
private String chk;
[...]//other fields
public String getChk() {
return chk;
}
public void setChkString chk) {
this.chk= chk;
}
[....] // other getters and setters }
Action class's execute method
[...]
MyFormBean myForm = (MyFormBean) form;
String chkVal = myForm.getChk();
[...]
Form Bean Entry in struts-config.xml
[...]
<form-bean name="myBean" type="pkg.MyFormBean"/>
[...]
Form Action Entry in struts-config.xml
[...]
<action path="/formAction" type="pkg.formAction" name="myBean" scope="request">
[...]

ModelAttribute not working with lists in spring

I want to bind a List using ModelAttribute. The list contains objects of type Transaction each of which contains transactionid (type int). This is my controller code:
#RequestMapping(value = "/approvecreditdebit.do", method = RequestMethod.POST)
public ModelAndView doActions(HttpServletRequest request,
#ModelAttribute("clc") Clc transactionList, BindingResult result,
ModelMap model) {
/*
* switch (action) { case "approve":
*/
System.out.println("Obj = " + transactionList.getClass());
System.out.println("Val = " + transactionList.getTransactionList());
Users users = new Users();
return new ModelAndView("internal","internal",users);
}
This is my jsp code:
<form:form action="approvecreditdebit.do" method="POST"
modelAttribute="clc">
<table border="1">
<tr>
<th>no</th>
<th>ID</th>
</tr>
<c:forEach items="${clc.transactionList}"
var="transaction" varStatus="status">
<tr>
<td>${status.index}</td>
<td><input name = "transaction[${status.index}].transactionId"
value="${transaction.transactionId}" /></td>
</tr>
</c:forEach>
</table>
<br>
<br>
<center>
<input type="submit" value="approve" />
</center>
</form:form>
This is the Clc class:
public class Clc{
private List<Transaction> transactionList;
public List<Transaction> getTransactionList() {
return transactionList;
}
public void setTransactionList(List<Transaction> transactionList) {
this.transactionList = transactionList;
}
}
The value of transactionList is not being set to the values received from the form. I receive the following error:
Request processing failed; nested exception is java.lang.NullPointerException
I tried searching for the solution on google and got a lot of solutions from stackoverflow but none of them seem to work.
Try something like this (notice the use of <form:input>). I just tried it on a simple Spring MVC app and it works (list is not null and has the values from the form when I try to access it in my POST method).
<c:forEach var="transaction" varStatus="status" items="${clc.transactionList}">
<tr>
<td>${status.index}</td>
<td><form:input path="transactionList[${status.index}].id" /></td>
</tr>
</c:forEach>

is it possible to add buttons dynamically and pass their values accordingly?

I am new to spring technology please help to solve this problem.
I am developing a web application in spring in which I have a leaveRecords.jsp page,and It should load following things,
For each records the page should display records into the table with two buttons like
<button id="Accept"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id()/>
<button id="Reject"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id()/>
After clicking on accept button relevant action will be performed and should redirect to same page but this time the page should contain button like
<button id="Cancel"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id() />
the leaveRecords.jsp is:
<form:form method="POST" action="upcomingLeaves.do" commandName="loginForm" modelAttribute="loginForm">
<% CommonDTOBean dtoBean=(CommonDTOBean)session.getAttribute("dtoBean");
List upcomingLeavesList=(ArrayList)session.getAttribute("upcomingLeavesList");%>
<table ><col><thead ><tr style="background-color:#666633;">
<th>Employee id</th>
<th>Leave Balance</th>
<th>Date</th>
<th>Leave Type</th>
<th>Leave Period</th>
<th>Applied Leaves</th>
<th>Status</th>
<th colspan="4">Action</th>
</tr></thead>
<tbody>
<%if(upcomingLeavesList!=null){
for(int i=0;i<upcomingLeavesList.size();i++){
dtoBean=(CommonDTOBean)upcomingLeavesList.get(i);%>
<tr>
<td ><span><%= dtoBean.getEmployee_id() %></span></td>
<td ><span><%= dtoBean.getNo_of_leave() %></span></td>
<td ><span></span><%= dtoBean.getFromDate() %>-<%= dtoBean.getToDate() %></td>
<td > <span><%= dtoBean.getLeaveType() %></span></td>
<td ><span></span><%= dtoBean.getLeavePeriod() %></td>
<td><span></span><%= dtoBean.getAppliedLeave() %></td>
<td><span></span><%= dtoBean.getLeaveStatus() %></td>
<td><button id="btnAccept" name="action" type="submit" value="Accept<%= dtoBean.getEmployee_id() %>" onclick="">Approve</button></td>
<td><button id="btnReject" name="action" type="submit" value="Reject<%= dtoBean.getEmployee_id() %>">Reject</button></td>
<td><button id="btnCancel" name="action" type="submit" value="Cancel<%= dtoBean.getEmployee_id() %>">Cancel</button></td>
</tr>
<%}}%>
</tbody>
</table>
</form:form>
Controller class is:
public String ApproveLeaves(#RequestParam(required=false , defaultValue="")String aion,#RequestParam(required=false,defaultValue="")String Cancel,HttpServletRequest request, HttpServletResponse response, ModelMap model){
try{
//following strings are used for getting the value of button and spiting it to get employee id
String buttonName=request.getParameter("action");
String buttonValue=buttonName.substring(0,6);// here we are spliting up the string and button name
int buttonValue1=Integer.parseInt(buttonName.substring(6));
if (buttonValue.equalsIgnoreCase("Reject"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
if (buttonValue.equalsIgnoreCase("Cancel"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
if (buttonValue.equalsIgnoreCase("Accept"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
return GlobalConstants.UPCOMING_LEAVES;
}
catch(Exception e)
{
System.out.println(e);
}
return GlobalConstants.ERRORPAGE;
}
service class has a method for db interaction:
public static boolean Approve(int id,String buttonValue,CommonDTOBean dtoBean2)
{
try {
con=DBConnection.getConnection();
String query="select no_of_leave from newemp_register where emp_id=?";//get available leaves from db
pstmt.executeQuery();
if(buttonValue.equalsIgnoreCase("Cancel"))
{
String approve="Update newemp_register set no_of_leave=? where emp_id=?";
pstmt.executeUpdate();
}
if(buttonValue.equalsIgnoreCase("Reject"))
{
return true;
}
if(buttonValue.equalsIgnoreCase("Accept"))
{
String approve="Update newemp_register set no_of_leave=? where emp_id=?";
pstmt.executeUpdate();
return true;
}
}
}//End Of while
} catch (Exception e) {
}
return false;
}//End of Approve
Please go through this example and help me I have tried very hard and searched on Google but could not solve it.
CommonDTOBean class:
public class CommonDTOBean {
private int emp_id;
private String Status;
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
Use JSTL for conditional rendering the DOM in jsp. like:
<form:form method="POST" action="upcomingLeaves.do" commandName="loginForm" modelAttribute="loginForm">
<table>
<thead>
<tr style="background-color:#666633;">
<th>Employee id</th>
<th>Leave Balance</th>
<th>Date</th>
<th>Leave Type</th>
<th>Leave Period</th>
<th>Applied Leaves</th>
<th>Status</th>
<th colspan="4">Action</th>
</tr></thead>
<tbody>
<c:choose>
<c:when test="${not empty upcomingLeavesList}">
<c:forEach items="${upcomingLeavesList}" var="upComLeave">
<tr>
<td><span>${upComLeave.emp_id}</span></td>
<td><span>${upComLeave.status}</span></td>
<td><span>${upComLeave.fromDate} - ${upComLeave.toDate}</span></td>
<td><span>${upComLeave.leaveType}</span></td>
<td><span>${upComLeave.leavePeriod}</span></td>
<td><span>${upComLeave.appliedLeave}</span></td>
<td><span>${upComLeave.leaveStatus}</span></td>
<c:if test="${upComLeave.leaveStatus ne 'accepted' }"> //check status if accepted, don't render Accept button
<td><button id="btnAccept" name="action" type="submit" value="Accept${upComLeave.emp_id}" onclick="">Approve</button></td>
</c:if>
<c:if test="${upComLeave.leaveStatus ne 'rejected' }">//check status if accepted, don't render Reject button
<td><button id="btnReject" name="action" type="submit" value="Reject${upComLeave.emp_id}">Reject</button></td>
</c:if>
<c:if test="${upComLeave.leaveStatus eq 'cancel' }">//check status if cancel, render cancel button
<td><button id="btnCancel" name="action" type="submit" value="Cancel${upComLeave.emp_id}">Cancel</button></td>
</c:if>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
upcomingLeavesList is empty or null..
</c:otherwise>
</c:choose>
</tbody>
</table>
</form:form>
Edit 1(based on comments):
If I click on approve the page should redirect with only Cancel and
Reject button
use one more if condition like:
<c:if test="${upComLeave.leaveStatus eq 'accepted' }">
<td><button id="btnReject" name="action" type="submit" value="Reject${upComLeave.emp_id}">Reject</button></td>
<td><button id="btnCancel" name="action" type="submit" value="Cancel${upComLeave.emp_id}">Cancel</button></td>
</c:if>
Note:
add this on top of jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Why do I get IllegalArgumentException Cannot convert value of type String to required type Product, in Spring?

I receive the exception
Failed to convert property value of
type [java.lang.String] to required
type [beans.Product] for property
product; nested exception is
java.lang.IllegalArgumentException:
Cannot convert value of type
[java.lang.String] to required type
[beans.Product] for property product:
no matching editors or conversion
strategy found
in the Errors errors object even before my DetailProductValidator starts validating through the validate method.
I don't understand why Spring does that. I don't have any input field that is mapped directly to the product property/object. I just use the product object's properties in the jsp. For example, I use:
<form:options items="${dpBackObj.product.colorMap}"/>
<!-- or -->
${dpBackObj.product.priceInDollars}
but I never use:
<form:input path="product"/>
Can anyone please explain why this happens? And maybe inform me of a simple solution?
The bean configuration for the controller is:
<!-- DETAIL PRODUCT FORM CONTROLLER -->
<bean id="productDetailFormController" name="/detail.htm /addToCart.htm"
class="detailProduct.DetailProductFormController">
<property name="sessionForm" value="true" />
<property name="commandName" value="dpBackObj" />
<property name="commandClass" value="detailProduct.DetailProductBackingObject" />
<property name="validator">
<bean class="detailProduct.DetailProductValidator" />
</property>
<property name="formView" value="detail" />
<property name="successView" value="redirect:/viewCart.htm" />
<property name="cartService" ref="cartServiceImpl"/>
</bean>
The backing object for the DetailProductFormController is:
public class DetailProductBackingObject {
private String quantityOverflowError;
private Product product;
private int quantity;
private ShoppingCart shoppingCart;
private long sizeId;
private long colorId;
public DetailProductBackingObject() {
this.product = new Product();
this.sizeId = -1;
this.colorId = -1;
}
//getters and setters
}
If you need some other info, I will provide. I am using Spring 2.5.5.
Kind Regards,
Despot
EDIT1 (due to request from axtavt):
<form:form method="post" commandName="dpBackObj">
<table width="730" border="0" cellspacing="0" cellpadding="0">
<c:if test="${!empty dpBackObj.quantityOverflowError}">
<tr>
<td>
<c:out value="${dpBackObj.quantityOverflowError}"/>
</td>
</tr>
</c:if>
<spring:bind path="dpBackObj.*">
<c:if test="${not empty status.errorMessages}">
<div class="val-summary text-error" id="errorDivId">
<div style="" class="val-summary text-error" id="errorDivId">
<fmt:message key="detail.error.header"/>
<ul>
<c:forEach items="${status.errorMessages}" var="error">
<li><c:out value="${error}"/></li>
</c:forEach>
</ul>
</div>
</div>
</c:if>
</spring:bind>
<tr>
<td width="310" align="left" valign="top">
<img src="${imagesPath}/${dpBackObj.product.largeImageUrl}" alt="${dpBackObj.product.description}" />
</td>
<td width="420" align="left" valign="top">
<div id="tls_detPName">
<c:out value="${dpBackObj.product.name}"></c:out>
</div>
<div >
<strong class="numeric">${dpBackObj.product.priceInDollars}</strong>
</div>
<div id="tls_detPDescLong">
${dpBackObj.product.largeDescription}
<br />
</div>
<div >
<table cellpadding="2" border="0">
<tr>
<td align="right">
<label for="p_sizes" class="label"><fmt:message key="viewCart.Size"/></label>
</td>
<td>
<form:select path="sizeId" >
<form:option value="-1" label="x"/>
<form:options items="${dpBackObj.product.sizeMap}"/>
</form:select>
</td>
</tr>
<tr>
<td align="right">
<label for="p_colors" class="label"><fmt:message key="viewCart.Color"/></label>
</td>
<td>
<form:select path="colorId" >
<form:option value="-1" label="y"/>
<form:options items="${dpBackObj.product.colorMap}"/>
</form:select>
</td>
</tr>
</table>
</div>
<div id="tls_addToCart">
<div >
<label for="quantityId" class="label"><fmt:message key="viewCart.Quantity"/>:</label>
<form:input path="quantity" onkeypress="return checkForNumber(this, event)" maxlength="10" size="3" id="quantityId" cssClass="textbox-center"/>
<input type="image" name="addToCartButtonName" src="${imagesPath}/addToCartBtn.jpg" />
</div>
</div>
</td>
</tr>
</table>
</form:form>
EDIT2 (due to JacobM's request):
This is my Validator:
public class DetailProductValidator implements Validator {
public boolean supports(Class clazz) {
return DetailProductBackingObject.class.equals(clazz);
}
public void validate(Object obj, Errors errors) {
DetailProductBackingObject detailProductBackingObject = (DetailProductBackingObject) obj;
if (detailProductBackingObject.getSizeId() == -1) {
errors.rejectValue("sizeId", "error.detail.jsp.choose.size", null, "Input size.");
}
}
}
When I reach the line DetailProductBackingObject detailProductBackingObject = I already have the error.
The converting of the request parameters to the backing object properties happens in http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/servlet/mvc/BaseCommandController.html . This is what Spring says about the conversion:
Populating using request parameters
and PropertyEditors: Upon receiving a
request, any BaseCommandController
will attempt to fill the command
object using the request parameters.
This is done using the typical and
well-known JavaBeans property
notation. When a request parameter
named 'firstName' exists, the
framework will attempt to call
setFirstName([value]) passing the
value of the parameter. Nested
properties are of course supported.
For instance a parameter named
'address.city' will result in a
getAddress().setCity([value]) call on
the command class.
It's important to realise that you are
not limited to String arguments in
your JavaBeans. Using the
PropertyEditor-notion as supplied by
the java.beans package, you will be
able to transform Strings to Objects
and the other way around. For instance
setLocale(Locale loc) is perfectly
possible for a request parameter named
locale having a value of en, as long
as you register the appropriate
PropertyEditor in the Controller (see
initBinder() for more information on
that matter.
Validators: After the controller has
successfully populated the command
object with parameters from the
request, it will use any configured
validators to validate the object.
Validation results will be put in a
Errors object which can be used in a
View to render any input problems.
Since I can't see anything wrong with the form, the only possible reason I can imagine is that you have a parameter named product in the URL of your form page.
If so, you can change your URLs or use DataBinder.setDisallowedFields() to disable the attempt to bind that parameter.

Resources