I have a dropdown list of users that I can assign to a WorkOrder. Where User to WorkOrder is a OneToMany relationship. The problem is how to assign a NULL value to a user Id ? If I don't set it to NULL it works fine and I can assign any name from the list.
If I use this code and pick NULL <form:option value="${null}" label="null" /> in my jsp i get an error:
Failed to convert property value of type java.lang.String to required type int for property user.id; nested exception is java.lang.NumberFormatException: For input string: ""
Here's my WorkorderDAOImpl
#Override
public void saveWorkOrder(WorkOrder theWorkOrder) {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
User user = theWorkOrder.getUser();
System.out.println("workorder: " + theWorkOrder);
System.out.println("user: " + user);
//save/update the work order
currentSession.saveOrUpdate(theWorkOrder);
}
My workorder-form.jsp I omitted some of the labels
<form:errors path="workorder.*"/>
<form:errors path="user.*"/>
<form:form action="saveWorkOrder" modelAttribute="workorder" method="POST">
<!-- need to assotiate the data with workorder id -->
<form:hidden path="id"/>
<table>
<tbody>
<tr>
<td><label>User name:</label></td>
<td><form:input path="user.userName"/></td>
</tr>
<tr>
<td><label>User:</label></td>
<td><form:select path="user.id">
<form:option value="${null}" label="null" />
<form:options items="${users}"
itemLabel="userName" itemValue="id"
/>
</form:select>
Turns out int in Java cannot be NULL so changed my id from int to Integer. Integer can be null.
I also added an if statement to my WorkOrderDAOImpl.java to check if user.id was set to null.
Here's my updated code.
#Override
public void saveWorkOrder(WorkOrder theWorkOrder) {
System.out.println(" \n Printing from WorkOrder : \n");
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
User user = theWorkOrder.getUser();
if (user.getId() == null) {
theWorkOrder.setUser(null);
}
//save/update the work order
currentSession.saveOrUpdate(theWorkOrder);
}
Related
I want to populate 3 selects (Zone, Station, Department) in struts2.
Each dropdown displays various options depending on value(s) selected in previous dropdown:
First field is Zone. User will select single Zone from zone select.
Based on this selected zone, station select will get populated from database.
User may select multiple stations here.
Based on these selected station(s), departments select tag will be populated from database.
Users may select multiple departments here.
I am able to populate zone select(dropdown) on page load and display it to jsp page.
However, station select is not displayed on my page, even though stationList attribute gets populated from database.
Setting it manually also does not help.
JSP Code here :
<tr>
<td style="background-color:#FFFFFF;" class="headingLabelStyle1" align="right">
<s:label value="Zone" ></s:label></td>
<td width="4%" align="center" class="headingLabelStyle1" style="background-color:#FFFFFF;">
<s:label value=":" /> </td>
<td style="background-color:#FFFFFF;">
<s:select name="pmrkpr8800Bean.zone" list="zoneList" id="zone"
headerValue="-- Please Select --" headerKey="-1"
tabindex="1" cssClass="h1"></s:select>
</td>
</tr>
<tr>
<td style="background-color:#FFFFFF;" class="headingLabelStyle1" align="right">
<s:label name="stncd" value="Station Code" ></s:label></td>
<td width="4%" align="center" class="headingLabelStyle1" style="background-color:#FFFFFF;">
<s:label value=":" /> </td>
<td style="background-color:#FFFFFF;">
<s:select name="pmrkpr8800Bean.stnCde" list="stationList" id="stnCde" headerValue="-- Please Select --" headerKey="-2" tabindex="2" cssClass="h1" size="3" multiple="true"></s:select>
</td>
</tr>
<tr>
<td style="background-color:#FFFFFF;" class="headingLabelStyle1" align="right">
<s:label value="Department" ></s:label></td>
<td width="4%" align="center" class="headingLabelStyle1" style="background-color:#FFFFFF;">
<s:label value=":" /> </td>
<td style="background-color:#FFFFFF;">
<s:select name="pmrkpr8800Bean.dept" list="deptList" id="dept" headerValue="-- Please Select --" headerKey="-1" tabindex="3" cssClass="h1" size="3" multiple="true"></s:select>
</td>
</tr>
public String populateZoneSelect() {
String result = SUCCESS;
try {
log.info("Inside populateZoneSelect");
zoneList = ipmrkpr8800.getZoneList();
} catch (Exception e) {
result = ERROR;
e.printStackTrace();
}
return result;
}
public String populateStationSelect() {
String result = SUCCESS;
String selZone = request.getParameter("selZone");
System.out.println("Selected zone: " + selZone);
try {
stationList.put("CSMT", "CSMT-MUMBAI");
stationList.put("NDL", "NDL-NEW DELHI");
stationList.put("PNVL", "PNVL-PANVEL");
} catch (IOException e) {
e.printStackTrace();
}
/*try {
log.info("Inside populateStationSelect");
stationList = ipmrkpr8800.getStationList(selZone);
System.out.println("StationList: " + stationList.size());
} catch (Exception e) {
result = ERROR;
e.printStackTrace();
}*/
return result;
}
Last two code blocks are from Action class. populateZoneList works fine and I am able to display different zones from database. Selected value is captured and sent to populateStationSelect(). if the commented part in the function is uncommented, stationList Map variable contains list of station codes and names.
But after that in jsp, in Station select tag only "Please Select" header value is displayed. The station codes and names retrireved from database are not displayed.
I have written getters and setters for these map variables also in action.
In my table, I've a row with checkbox which tells the controller whether that particular row of the table has to be included or no. The check box does not have relation with other rows. I tried adding it in the following way :
<form:form id="fee" method="post" modelAttribute="clientForm" commandName = "clientForm"
action="<%= request.getContextPath().toString()%>/addFee.do">
<TABLE>
<tr>
<c:forEach var="type" items="${clientInfo}" varStatus="status">
<td><form:checkbox class="editable${ifeeCount}" path="includeFeeValue" value="false"/> </td>
<td>feeType<c:out value = "${status.index}"/></td>
<td>Source Fee<c:out value = "${status.index}"/></td>
<td><form:input class="editable${ifeeCount}" disabled="true" path="overriddenFee" /></td>
<td><form:errors path="overriddenFee" cssClass="error" /></td>
</c:forEach>
</tr>
</TABLE>
And in my form, I've a list private ArrayList<String> includeFeeValue;
And i'm trying to retrieve this in the spring controller class as follows :
#RequestMapping(value="/addFee.do",method = RequestMethod.POST)
protected #ResponseBody ModelAndView selectValues(#ModelAttribute("clientForm") PaswFeeMaintenanceForm MyMaintForm ) throws Exception {
for(int i=0;i<MyMaintForm.getIncludeFeeValue().size();i++){
System.out.println("Checkbox : "+MyMaintForm.getIncludeFeeValue().get(i)+ " of "+i);
}
}
Once I submit my form, it throws null pointer exception in here : MyMaintForm.getIncludeFeeValue().size() .
Could you tell me what's missing here?
Remove disabled='true' and it will work. I faced the same problem with my textfield with property disabled as true.
And also use private String[] includeFeeValue instead of List.
As your checkbox is disabled, ans disabled elements values never flow to controller or Servlet. I advise you to remove a disabled attribute. I hope so it will work.
The goal: adding multiple table rows dynamically based on user inputs and catch the data through controller.
What I have so far(all simplified):
POJO:
public class Item(){
String price;
String weight;
getters and setters...
}
public class ItemForm(){
List<Item> items;
getter and setter...
}
JSP:
<form:form action="/create" method="POST" modelAttribute="itemForm">
<table>
<tr>
<td><input type='text' name='price'/></td>
<td><input type='text' name='weight'/></td>
</tr>
</table>
<c:forEach items="${itemForm.items}" var="item" varStatus="status">
<tr>
<td align="center">${status.count}</td>
<td><input name="items[${status.index}].price" value="${item.price}" /></td>
<td><input name="items[${status.index}].weight" value="${item.weight}" /></td>
</tr>
</c:forEach>
</form:form>
Controller:
private List<Item> items = new ArrayList<>();
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String saveMultipleRows(#ModelAttribute("itemForm") ItemForm itemForm) {
items = itemForm.getItems();
if(items != null && items.size() > 0){
System.out.println("The list is not null!");
}
System.out.println("didn't get into the if statement");
return null;
}
I skipped the Javascript on adding table rows, if you think that have anything to do with this question, I will update my post and put the Javascript code.
The idea is to create a ItemForm class that contains a list of Item object, and in the JSP using JSTL c:foreach to save all the data from users to the list. And in my controller, if the list is not empty, I simply want to print out a message so that I know the list is not empty. But now if I run the program, it prints out "didn't get into the if statement".
So the problem I am currently having is the list is empty, that means I am not able to save the user input data to the list. Can anyone help me and let me know where I did wrong?
Below is the corrected code
since you have item in scope you can directly access the props of Item,You dont need to explicitly declare the index
<input name="${item.price}" value="${item.price}" />
<input name ="${item.weight}" value="${item.weight}" />
My code snippets are as below :
ShopRegister2.jsp :
<%
session = request.getSession();
session.setAttribute("s_id", s_id);
out.println("Your id is : "+s_id);
%>
<br>
Please note it for further use.!<br>
<form name="register" method="post" onsubmit=" return reg_form()" action="ShopRegister3.jsp"><br>
Enter your name : <input type="text" name="s_name" id="s_name"><br>
Enter your Location : <input type="text" name="s_location" id="s_location"><br>
Enter your password : <input type="password" name="s_password" id="s_password"> <br>
Confirm Password : <input type="password" name="c_s_password" id="c_s_password"><br>
<input type="submit" value="Submit"><br>
</form><br>
ShopRegister3.jsp :
String s_name=null, s_password=null, s_location=null;
int s_id = 0;
session.setAttribute("s_name", s_name);
session.setAttribute("s_password", s_password);
session.setAttribute("s_location", s_location);
String s_id_string=(String)request.getParameter("s_id");
s_id = session.getAttribute("s_id") != null ? (Integer) session.getAttribute("s_id") : 0 ;
s_name=(String)session.getAttribute("s_name");
s_password=(String)session.getAttribute("s_password");
s_location=(String)session.getAttribute("s_location");
//entering values into Shop table
PreparedStatement s_insert = con.prepareStatement("insert into ShopSystem.Shop values(?,?,?,?)");
s_insert.setInt(1, s_id);
s_insert.setString(2, s_password);
s_insert.setString(3, s_location);
s_insert.setString(4, s_name);
int c = s_insert.executeUpdate();
//checking whether the value was inserted successfully
if(c>0)
{ %>
S_ID = <%= s_id %> has been registered successfully.<br>
<% response.sendRedirect("ShopMenu3.jsp");
} %>
In the above code the server is directing to ShopMenu3.jsp after running ShopRegister3.jsp
Yet in my database, null values are being entered for the attributes : name, password and location.
I have tried many things..., where exactly seems to be the error?
Your session variables are always set to null;
Use:
s_name=(String)request.getParameter("s_name");
s_password=(String)request.getParameter("s_password");
s_location=(String)request.getParameter("s_location");
To get the values before setting them in the session
Maybe that is the problem?
String s_name=null, s_password=null, s_location=null;
And then you set session to this null values.
You have to first request that parameter before setSession statement;
so in ShopRegister3.jsp, after s_name initialization to `nullĀ“.
Request that parameter like:
s_name = request.getParameter("s_name");
Now you can setSession for this variable; it will not return null for s_name variable now.
I would like to save an object C from a form. This form contains of two select drop downs each represents class A and class B.
Class C has a connection to class A and class A has a list connection to class B.
When I save object C from form I choose one item from select drop down class A and one item from class B.
The new ID of C and the choosen ID of A is saved to a db table db_C and choosen ID of B is supposed to be saved together with newly created ID of C and a new ID of D to a db table db_D which contains connections to B and C.
Table db_A
__A__
1
2
3
Table db_B
__B__|__C__
4 | 2
5 | 1
Table db_C
__C__|__A__
1 | 2
2 | 3
Table db_D
__D__|__B__|__C__
1 2 1
I have a controller of C:
#RequestMapping(value = "/new", method = RequestMethod.GET)
public String add(Model model) {
model.addAttribute("listOfAs", listOfAs());
model.addAttribute("C", new C());
model.addAttribute("listOfBs", listOfBs());
return "C/edit";
}
private List<B> listOfBs() {
List<B> listOfBs = new ArrayList<>();
try {
listOfBs.addAll(BService.listBs());
} catch(DataAccessException ex) {
logger.error(ex.getMessage(), ex);
}
return listOfBs;
}
private List<A> listOfAs() {
List<A> listOfAs = new ArrayList<>();
try {
listOfAs.addAll(AService.listAs());
} catch (DataAccessException ex) {
logger.error(ex.getMessage(), ex);
}
return listOfAs;
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String update(Model model, #ModelAttribute("C") C C, BindingResult CResult) {
C.setA(AService.getA(C.getA().getID()));
System.out.println(C.getA().getBs().isEmpty()); //Prints "True"
if (C.getID() == 0) {
CService.save(C);
} else {
CService.update(C.getID(), C);
}
return "redirect:/mvc/C/viewList";
}
And my form of C
<s:url value="/mvc/C/save" var="actionUrl" />
<sf:form method="POST" modelAttribute="C" action="${actionUrl}">
<fieldset>
<table>
<tr>
<th><label for="A">A:</label></th>
<td><sf:select path="A.ID">
<sf:option value="0"> </sf:option>
<sf:options items="${listOfAs}" itemLabel="name" itemValue="ID" />
</sf:select></td>
</tr>
<tr>
<th><label for="B">B:</label></th>
<td>
<sf:select path="A.listRefToB">
<sf:option value="0"> </sf:option>
<sf:options items="${listOfBs}" itemLabel="name" itemValue="ID" />
</sf:select>
</td>
</tr>
<tr>
<td colspan="2">
<input id="saveButton" class="right" type="submit" title="Save" value=" [ Save ] " />
</td>
</tr>
</table>
</fieldset>
</sf:form>
The problem is that when I save I get an empty list of Bs. I think it's because C doesn't have a direct reference to B. But I'm not sure. I really need help with this! How do get selected value of B into the save-function??
I've tried these two links with no result
List<Foo> as form backing object using spring 3 mvc, correct syntax?
How to send list of Objects to View and back to Post method in controller
I didn't get the names and id's into the optiontag.
The goal in this is to choose A and B in the form for C and on save I'd like to save all values I enter in form to db_C and db_D respectivly.
I hope someone can help me :)
I edited the question because the first one was a bit confusing.
I created a new class AFormatter with a print and a parse function. That did the trick!