list of string not displayed - java

I use spring 3. I'm trying to display a value of an object in a jsp.
public class UserForm implements Serializable {
private List<String> values;
private String date;
...
}
Here is my controller:
#Controller
#RequestMapping("/user.htm")
public class UserController {
#Autowired
private IUserService userService;
#RequestMapping(method = RequestMethod.GET)
public String userStat(Model model) {
UserForm stat = userService.populateStatistique();
stat.setDate("today");
model.addAttribute("statistiqueForm", stat);
return "userStat";
}
}
Here is my jsp:
<form:form commandName="userForm" name="userForm">
Date: <form:input path="date"></form:input>
<br/>
Expediteur:
<form:select path="values" items="${values}" />
<br/>
<input type="submit" value="create" />
</form:form>
In the jsp I can see the today value for the date field, but the listbox is empty.
any idea?
thanks

Well, use addAttribute("values", list) if you want it accessible in the jsp. You are currently not setting it and so it is empty.
If that list is contained in the statistiqueForm object, then use items="${statistiqueForm.values}".

You're correctly passing the form object to the jsp page. In that page you have a list box, which has a list of potential values and a list of selected values. The object form contains the list of selected values, but you should also setup the list with all potential values. In fact you reference ${values} in the jsp, but you don't pass it to the jsp. You should add this code to your controller:
model.addAttribute("values", potentialValueList);
I also suggest you to change the name of that list to avoid confusion, so it will be easy to understand the difference from selected values to potential values.

Related

Problem with th:each in <select> HTML tag. Thymeleaf and Spring

So I've made this simple project in Intellij idea.
I'm filling array with next elements:
public class formClass {
private String list[] = {"+", "-", "x", "/"};
public String[] getList() {
return list;
}
}
This is controller section. Here i'm adding formClass object as a model attribute:
#Controller
public class GreetingController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String greeting(#RequestParam(name="name", required = true, defaultValue = "null") String name, Model model){
model.addAttribute("name", name);
model.addAttribute("form_class", new formClass());
return "greeting";
}
}
greeting.html
<form id="form1" action="#" th:action="#{/}" th:object="${form_class}" method="POST">
<select th:field="*{list}" class="formable">
<option th:each="i : *{list}" th:value="${i}" th:text="${i}"></option>
</select>
</form>
everything works fine, except that all options are marked with selected attribute therefore the last item is automatically selected, which i try to avoid and can't figure out where i'm going wrong
i'll be glad for any help, thank you!
Try th:selected for selecting default option.
Please use below syntax
<option th:each="i : ${list}" th:value="${i}" th:text="${i}" th:selected="${ i==\"+\"" }></option>
Hope this will work.
solution was the simplest, i just removed th:field from select tag and set th:selected to the '+' option as Laminoo Lawrance recommended

How do I copy data from on table to another in spring boot?

I am currently making an application that lets you create students, and then mark them absent. I want to be able to do this by adding it into a separate table called AbsentStudents. But with the jparepository or the crudreposotroy don't give me these options.
I tried to create a new entity that was a replica of the students entity, then make the dao equal the findbyid of the student. it looked like this:
dao.equals(repo.findById(id));
Index.jsp:
<body>
<p> Add a student into the database:<p>
<form action ="addStudent">
<input type = "text" name = "ID"><br>
<input type = "text" name = "Name"><br>
<input type = "text" name = "Teacher"><br>
<input type = "submit">
</form>
<p> Mark a Student Absent<p>
<form action ="markAbsent">
<input type = "text" name = "ID"><br>
<input type = "submit">
</form>
</body>
</html>
Then the absentStudent, which is the same as student
#Entity
#Getter
#Setter
public class AbsentStudent
{
#Id
private int id;
public int getId() {
return id;
}
}
I then created the dao of both the student and absent.
Finally, here is the controller. I left the autowired out.
#RequestMapping("/addStudent")
public String addStudent(Student student) {
repo.save(student);
return "index.jsp";
}
#RequestMapping("/markAbsent")
public ModelAndView markAbsent(#RequestParam int id) {
ModelAndView mv = new ModelAndView();
dao.equals(repo.findById(id));
mv.setViewName("absent.jsp");
mv.addObject(dao);
return mv;
}
}
I was expecting a page in the end, which would fetch all the absent students from the database, and post them on a single page. But, I get an error page.
the data didn't copy from student to absent student.
I want to be able to do this by adding it into a separate table called AbsentStudents. But with the jparepository or the crudreposotroy don't give me these options.
Maybe #Query annotation inside dao (repository) interface will help with your problem ( https://www.baeldung.com/spring-data-jpa-query )

How to bind nested List object to JSP form?

Hello fellow programmers,
I am writing a Spring MVC application for students to do an online assessment with multiple choice questions. An admin should be able to create assessments, so I created this object structure:
#Entity
#Table(name = "assessment")
public class Assessment {
private List<Question> questions;
// getter and setter
}
#Entity
#Table(name = "question")
public class Question {
private String questionText;
private List<Answer> answers;
// getters and setters
}
#Entity
#Table(name = "answer")
public class Answer {
private String answerText;
private boolean isCorrect;
// getters and setters
}
Now, I am using a JSP form on the admin page:
Controller
#RequestMapping(value = "/add/assessment", method = RequestMethod.GET)
public String addAssessments(Model model) {
model.addAttribute("assessmentModel", new Assessment());
return "admin-assessments-create";
}
JSP form
<form:form method="POST" modelAttribute="assessmentModel">
<form:input path="questions[0].questionText" type="text"/> <!-- this is working-->
<form:radiobutton path="questions[0].answers[0].isCorrect"/> <!-- not working-->
<form:input path="questions[0].answers[0].answerText"/>
<button class="btn" type="submit">Submit</button>
</form:form>
When I go to this page I receive the following error:
org.springframework.beans.NotReadablePropertyException:
Invalid property 'questions[0].answers[0].isCorrect' of bean class [com.johndoe.model.Question]:
Bean property 'questions[0].answers[0].isCorrect' is not readable or has an invalid getter method:
Does the return type of the getter match the parameter type of the setter?
I checked all the getters and setters but those are perfectly fine.
Question:
how do I avoid the NotReadablePropertyException and thus bind the nested Answer List to my form?
Use
<form:radiobutton path="questions[0].answers[0].correct"/>
and it will be working.
Why? For boolean fields you have to adapt the get/set paradigm to "is"XYZ(). For the EL expression, you have to drop the "is" in front of the method that accesses the current value of the field, pretty much the same way, you would do with "get" / "set".

How do I pass the dropdown select value to a button click in the controller and search against the value in data base?

here is the controller
#RequestMapping(value = "/submitrule", method = RequestMethod.POST)
public String addruleSerch(#ModelAttribute("SpringWeb") Rule obj2, ModelMap model) {
model.addAttribute("Select", obj2.getId());
System.out.println("********" + obj2.getId());
ruleApi.getRule(obj2.getId());
model.addAttribute("listrule", ruleApi.getRule(obj2.getId()));
return "redirect:/hello";
}
here is the html....
<form action="/CommissionTool/submitrule" method="post">
<table>
<tr>
<td><select name="Select"><c:forEach items="${listRules}" var="rule">
<option value="${rule.id}">
<c:out value="${rule.id}" />
</option>
</c:forEach>
</select>
</td>
<td><input type="submit" onClick="addRow('in_tbl_name')" VALUE="Add New"></td>
</tr>
</table>
</form>
How could i fix this.. please help me
Thanks in Advance...
Well you need to do several changes in your code, but is pretty near.
You need to send the object you want to use as modelAttribute to the view the first time.
In your html you need to say to the form which is the object to render, your model attribute
Create a POST method in your controller to retrieve the object
Lets put all together in this this example. I have a class called RuleForm, which contains an attribute of type Rule.
public class RuleForm {
...
#Getter #Setter //here use lombok, but you could create your getters-setters methods
private Rule rule;
...
}
Now in the controller, into the GET method, we set the view resolver(JSP) and the object we will send to there. In this case an object of type FormRule
#RequestMapping(value = "/submitrule", method = RequestMethod.GET)
public ModelAndView addruleSerch() {
ModelAndView model = new ModelAndView("yourView");
//here you choose the name you will use in your view, is up to you the name to choose
model.addObject("formRule", new FormRule());
return model;
}
Now we need to pick up that object we sent to the view and use it into our form tag.
<form action="/CommissionTool/submitrule" method="post" model="formRule">
...
<select name="rule.id"><c:forEach items="${listRules}" var="rule">
<option value="${rule.id}">
<c:out value="${rule.id}" />
</option>
</c:forEach>
</select>
In this point when we send the form to the Controller, we will send the RuleForm object with a value into rule.id object, then in the controller we have to get that id value and add out business logic.
#RequestMapping(value = "/submitrule", method = RequestMethod.POST)
public String addruleSerch(#ModelAttribute RuleForm ruleForm) {
//Here you will have access to your object
ruleForm.getRule().getId();// rule selected in the form
... your business logic
return "redirect:/someUrl";
}

Spring: How to register converter/editor for nested list of objects

I have quite complicated html form and I'm trying to map it to models. Form contains information about Board (name, date, owner, etc...) and list of Items. Each item contains some data too. Items are added/deleted dynamically so I use JS to add indexes before form is sent. Here is part of my form:
<div>
<label>Link:</label>
<input type="text" name="items[<index>].link">
<label>JScript:</label>
<select name="items[<index>].javaScript">
<option>disable</option>
<option>enable</option>
</select>
</div>
I use form's onsubmit function to change to appropriate value. It maps fine for my model which is Board with List of items:
public class Board
{
private long id;
private User owner;
private String title;
private List<Item> items;
...
}
what I would like to do is register custom editor or converter for List because I need to do some manual changes.
I've tried
binder.registerCustomEditor(Item.class, "items", new PropertyEditorSupport()
and
binder.registerCustomEditor(List.class, "board.items", new CustomCollectionEditor(List.class)
but it doesn't work at all.

Categories

Resources