Could you please assist me for the following code? I am trying to get ENUM values into dropdown but dropdown displayes nothing.
create.jsp
<select name="labOwner" name="labOwner" id="labOwner">
<option value="Select"></option>
<c:forEach var="labOwner" items="${labOwner}">
<li>${labOwner}</li>
</c:forEach>
</select>
LabController.java
#RequestMapping(value = "/lab/labOwner")
public ModelAndView getPages(){
List<LabOwner> labOwner = new ArrayList<LabOwner>( Arrays.asList(LabOwner.values() ));
ModelAndView model = new ModelAndView("create");
model.addObject("labOwner", labOwner);
return model;
}
LabOwner.java
public enum LabOwner {
G_ONLY("G"),
D_ONLY("D"),
GS("S/D ");
private String labOwner;
LabOwner(String labOwner) {
this.labOwner = labOwner;
}
public String getLabOwner() {
return labOwner;
}
You can use the spring form tag to bind your property:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:select path="labOwnerBeanPropertyNameHere" id="labOwner">
<c:forEach var="labOwnerValue" items="${labOwner}">
<form:option value="${labOwnerValue}">${labOwnerValue}</form:option>
</c:forEach>
</form:select>
Note that you'll want to display the value of each item in your labOwner list, rather than the list as a whole.
Also, your controller code can be simplified to:
#GetMapping("/lab/labOwner")
public String getPages(Model model){
model.addAttribute("labOwner",
new ArrayList<LabOwner>(Arrays.asList(LabOwner.values());
return "create";
}
Finally, take a look at Project Lombok and use the #Getter annotation for your Enum class.
Related
i am trying to get question and it's multiple options. i am getting successfully Question but its options getting null.
<c:forEach begin="0" end="${optionsCount}" varStatus="loop">
<form:input path="options[${loop.index}].mcq"/>
</c:forEach>
public class OnlineTestQuestionBean {
private String optionsCount;
private Long questionId;
private String question;
private Set<QuestionOptionBean> options;
//setter getter
}
public class QuestionOptionBean {
private Long optionId;
private String mcq;
//setter getter
}
following is Controller Code :-
#Controller
public class OnlineTestController {
#RequestMapping(value = "/savequestion", method = RequestMethod.GET)
public String addQuestion(Model model) {
model.addAttribute("OnlineTestQuestionBean", onlineTestQuestionBean);
return "addquestion";
}
#RequestMapping(value = "/savequestion", method = RequestMethod.POST)
public String saveQuestion(#ModelAttribute("OnlineTestQuestionBean")OnlineTestQuestionBean onlineTestQuestionBean, Model model) {
return null;
}
}
Following is Spring Form code :-
<c:forEach begin="0" end="${optionsCount}" varStatus="loop">
<form:input path="options[${loop.index}].mcq"/>
</c:forEach>
When i submit that time i get "Cannot get element with index 0 from Set of size 0, accessed using property path" this Exception,
suppose i used following code i get null set value.
<input type="text" path="options.mcq"/>
Try using the following in the form :
<c:forEach
<c:forEach items="${options}" var="option">
<form:input path="option.mcq"/>
</c:forEach>
In my Controller I have
#RequestMapping(value="/getCounties", method = {RequestMethod.GET},produces=MediaType.Application_JSON_VALUE)
public #Responcebody List<Counties>(#RequestParam String province){
List<Counties> county = this.xService.getCounties(county);
return county;
}
This method send the province chosen in the form down to the repository and join on the counties within that province.
In my dropdown on the form how do I return these values into the dropdown.
I currently have
<tr>
<td>
<form:select path="cdGcd" class="textbox" onclick="getCounty()">
<form:option value="-" label="Please Select"/>
<form:options path="county" items='${county}' itemValue = "countycode" itemLabel="countydescription"/>
</form:select>
</td>
</tr>
You can not return List directly form controller.
For passing data from controller to JSP you need to add data in Model and return respective JSP page.
So you need to change your method to,
#RequestMapping(value="/getCounties", method = {RequestMethod.GET})
public String getCountries(#RequestParam String province, Model model){
List<Counties> county = this.xService.getCounties(county);
model.addAttribute("county",county);
return "jsp page";
}
If you want to achieve this using AJAX then,you need to return JsonObject from controller.
register.jspx
<form action="register" id="user" method="POST">
<form:select path="factory">
<form:options itemValue="id" itemLabel="name" items="${factory}" />
</form:select>
</form>
model
public class Factory {
#Size(max = 255)
private String name;
}
controller
#RequestMapping(method = RequestMethod.POST, produces = "text/html",value = "/register")
public String UsersController.register(#Valid Users users,UserData userData,Factory factory,BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
if (bindingResult.hasErrors()) {
Logger.getGlobal().log(Level.WARNING, bindingResult.getAllErrors().get(0).toString());
populateRegisterForm(uiModel, users);
return "userses/register";
}
uiModel.asMap().clear();
userData.setFactory(factory);
userData.persist();
users.setUserData(userData);
users.persist();
return "redirect:/userses/" + encodeUrlPathSegment(users.getId().toString(), httpServletRequest);
}
and html output
<select>
<option value="1">aa</option>
<option value="2">bbbbbbbbbbbb</option>
</select>
Select tag haven't name veriable in html output. but i edited jspx file with path="factory"
You need to enclose your form:select within a Spring form:form, and not just an ordinary form.
I'm pretty sure your JSP won't compile after you make that change - it looks like you may have other errors, but hard to tell without seeing the rest of your domain. Can you also add the controller handler/action that is called to produce the form view.
Is there an easy way in Spring MVC 3.x to display form error messages (obtained by JSR303 validation), before submiting the form ?
Consider the example code at the end of this post.
The end-user is supposed to edit forms in which the initial data is already invalid.
Errors are properly displayed when the form is submitted (POST method), but not on initial form display (GET method).
Is there an easy way to display the errors on initial form display (GET method) ? (Is there a way to re-use the form:errors tag for this purpose?)
JSP View form1.jsp:
<%# page session="true" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html><body>
<form:form commandName="form1" method="post">
<s:bind path="*">
<c:if test="${status.error}">
<div style="color: red;">There are errors:</div>
<form:errors /><br />
</c:if>
</s:bind>
<form:label path="field1" >Field1:</form:label>
<form:input path="field1" />
<form:errors path="field1" cssStyle="color: red;"/>
<br />
<form:label path="field2" >Field2:</form:label>
<form:input path="field2" />
<form:errors path="field2" cssStyle="color: red;"/>
<br />
<form:button name="submit">Ok</form:button>
</form:form>
</body></html>
Controller:
#Controller #SessionAttributes("form1")
public class Form1Controller {
#ModelAttribute("form1") public Form1Bean createForm1() { return new Form1Bean(); }
#RequestMapping(value = "/form1/edit", method = RequestMethod.GET)
public String getEdit(Model model) {
// here we pretend to get form1 from database, and store it in session.
// form1 in database may have invalid field values.
// Perform a JSR-303 validation here ?
// MAIN QUESTION: What's the easy way to add errors to model and display them ?
return "/form1";
}
#RequestMapping(value = "/form1/edit", method = RequestMethod.POST)
public String postEdit(#Valid #ModelAttribute("form1") Form1Bean form1, BindingResult result, Model model) {
if (result.hasErrors()) {
return "/form1";
} else {
return "redirect:/done";
}
}
}
Backing Bean:
public class Form1Bean {
#Size(min=4,max=10) private String field1; // getters and setters ommited for brevity
#Size(min=4,max=10) private String field2;
public Form1Bean() {
this.field1 = "bad"; this.field2="good"; // start with an invalid field1
}
//...
}
Edit: After the interpreting the answer from #jb-nizet, here is the complete controller source:
#Controller #SessionAttributes("form1")
public class Form1Controller {
#Autowired org.springframework.validation.Validator validator;
#ModelAttribute("form1") public Form1Bean createForm1() { return new Form1Bean(); }
#RequestMapping(value = "/form1/edit", method = RequestMethod.GET)
public String getEdit(#ModelAttribute("form1") Form1Bean form1, Errors errors, Model model) {
// here we pretend to get form1 from database, and store it in session.
// form1 in database may have invalid field values.
validator.validate(form1, errors);
return "/form1";
}
#RequestMapping(value = "/form1/edit", method = RequestMethod.POST)
public String postEdit(#Valid #ModelAttribute("form1") Form1Bean form1, BindingResult result, Model model) {
if (result.hasErrors()) {
return "/form1";
} else {
return "redirect:/done";
}
}
}
Made a few tests, and it seems to work! Than you #jb-nizet
Not tested, but as I understand the documentation, you would just have to inject an object of type org.springframework.validation.Validator in your controller, create and bind an Errors instance as explained in Add Error on GET METHOD Spring annotated controller, and invoke the validator's validate() method, passing the form and the Errors as argument.
I'm using a multiple select HTML form input to allow a user to pick a collection of Extensions from a list of all possible Extensions.
The Extension class is quite simple -
public class Extension {
private String number;
private String firstName;
private String lastName;
... getters and setters ...
#Override
public String toString() {
return new StringBuilder(number).append(" - ")
.append(firstName).append(" ").append(lastName)
.toString();
}
}
Here's my form object -
public class BusinessUnitForm {
private String name;
private Collection<Extension> extensions;
public Collection<Extension> getExtensions() {
return extensions;
}
public void setExtensions(Collection<Extension> extensions) {
this.extensions = extensions;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And the controller -
#Controller
#RequestMapping("/businessunit")
public class BusinessUnitController {
... extension service & getters/setters ...
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
Integer customerId = (Integer) request.getSession().getAttribute("customerId");
ModelAndView mav = new ModelAndView("bu");
// this is quite expensive...
Collection<Extension> allExtensions = extensionService.getAllExtensions(customerId);
BusinessUnitForm businessUnitForm = new BusinessUnitForm();
mav.addObject("allExtensions", allExtensions);
mav.addObject("businessUnitForm", businessUnitForm);
return mav;
}
#RequestMapping(value="/create", method = RequestMethod.POST)
public ModelAndView create(HttpServletRequest request, HttpServletResponse response, BusinessUnitForm businessUnitForm, BindingResult result) throws Exception {
// *** BREAKPOINT HERE *** to examine businessUnitForm
Integer tenantId = (Integer) request.getSession().getAttribute("tenantId");
// code to process submission
ModelAndView mav = new ModelAndView("bu");
return mav;
}
}
And finally the view -
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<html>
...
<form:form action="businessunit/create" method="POST" commandName="businessUnitForm" >
<form:label path="name"></form:label><form:input path="name" />
<form:select path="extensions" cssClass="multiselect">
<form:options items="${allExtensions}" itemValue="number" />
</form:select>
<input type="submit" value="Create" />
</form:form>
...
</html>
At the breakpoint shown above in the create controller method, businessUnitForm.extensions is null. businessUnitForm.name is bound correctly.
I've tried, perhaps misguidedly, making businessUnitForm.extensions a LazyList but this doesn't help.
If I change BusinessUnitForm.extensions to be a Collection of unspecified type, it is populated successfully with a LinkedHashSet of Strings, containing the values selected.
Maybe I'm expecting too much of Spring, but I was hoping it would be able to use the values from the select, and also the reference data in allExtensions to automagically create a Collection<Extension> for me on the businessUnitForm. I understand the role of CustomCollectionEditors, but was under the impression that this might not be required in Spring 3.
Can Spring 3 populate my Collection<Extension> on the BusinessUnitForm without me writing a custom collection editor ? Some kind of trick with the view, perhaps ?
Thanks in advance ...
Dan
You need to implement a custom converter that is able to convert the String from the request into an Extension object.
And then you must use Collection (or List, or Set) with generic type information.
See this answer for an example of an converter: Submit Spring Form using Ajax where Entity has Foreign Entities