How to display ArrayList Object in Thymeleaf page - java

I try to display Arraylist object in Thmeleaf page but I got null for the value.
I can display the arraylist in controller on console. Is it correct the way I pass arraylist in function.
In controller
#RequestMapping("/searchSummon")
public String Search(Model model) {
model.addAttribute("summonsDetailType", new SummonsDetailType());
model.addAttribute("rowType", new RowType());
return "searchSummon";
}
#RequestMapping(value = "/searchProcess", method = RequestMethod.POST)
public String searchProcess(SummonsDetailType summonsDetailType, RowType rowType) {
ArrayList<RowType> rowTypes2 = new ArrayList<RowType>();
SummonsDetailType summonsDetailType2 = pdxiRes.getRequest().getSummonsDetail();
for (RowType rowType3 : summonsDetailType2.getRow()) {
rowTypes2.add(rowType3);
}
System.out.println(rowTypes2.get(0).getDistrictCode());
return "/searchResult";
}
html page
<tr th:each="rowType : ${rowType}">
<td th:text="'NRIC NO: ' + ${rowType.DistrictCode}"></td>
</tr>

I solved the problem by adding the arraylist in model
model.addAttribute("rowTypes2", rowTypes2);

Related

How to show one Item at a time from Java ArrayList

I wonder if anyone can help, I'd like to Iterate over ArrayList but One item at a time with help of some button so when I press that button it would show me the next item in the list and so forth. Or if there's another way I'd be happy to take any advice. I'm trying to design a test so a student would get one question at a time he/she would submit the answer and it would move to the next question. This is what I have as showing full list on JSP.
My Servlet
String vassId = request.getParameter("vassId");
List<Assessment> qList = new ArrayList<Assessment>();
Assessment qObj = null;
DbConnection dbConn = null;
Connection conn = null;
CallableStatement proc = null;
response.setContentType("text/html");
ResultSet rs = null;
try {
dbConn = new DbConnection();
conn = DbConnection.connection();
String dbCall = "{ ? = call pa_customer_admin.fn_list_question(?) }";
proc = DbConnection.connection().prepareCall(dbCall);
proc.registerOutParameter(1, OracleTypes.CURSOR);
proc.setInt(2, Integer.parseInt(vassId));
proc.execute();
rs = (ResultSet) proc.getObject(1);
while (rs.next()) {
qObj = new Assessment();
qObj.setVassId(Integer.parseInt(rs.getString(1)));
qObj.setDescr(rs.getString(2));
qObj.setQuesStatus(rs.getString(3));
qObj.setQuesTypeCode(rs.getString(4));
qObj.setCreatedDate(rs.getString(6));
qObj.setQuestion(rs.getString(7));
qObj.setMark(rs.getString(8));
qObj.setTimeLimit(rs.getInt(9));
qList.add(qObj);
}
request.setAttribute("qObj", qObj);
request.setAttribute("qList", qList);
proc.close();
JSP
<form action="AnswerSaveProcess" method="POST" >
<c:if test="${empty qList}">
Empty list
</c:if>
<c:if test="${! empty qList}">
<c:forEach items="${qList}" var="q">
<label>Question</label>
<input type="hidden" value="<%= vassId%>">
<textArea readonly="readonly">${q.question}</textarea>
<input type="text" value="${q.mark}" readonly="readonly">
<input type="hidden" id="userTime" value="${q.timeLimit}" />
<label>Answer 1</label>
<input type="text" ><input name="ansStatusCode" type="radio"><br/>
<label>Answer 2</label>
<input type="text" ><input name="ansStatusCode" type="radio"><br/>
<input type="submit" name="submit" value="Save Answer">
</c:forEach>
</c:if>
</form>
ArrayList implements the Iterable interface and has index-based access to its members. All you need is to read some Java docs on usage examples.
Try something like (untested):
final List<String> questions = Arrays.asList(new String[]{"question1", "question2", "question3"});
JButton b = new JButton("Press Me");
final JLabel label = new JLabel();
final cnt = 0;
b.addActionListener(new ActionListener(){
pubic void actionPerformed(ActionEvent e) {
label.setText(question.get(cnt++));
if(cnt > questions.size()) cnt = 0;
}
});
JFrame frame = new JFrame();
frame.getConentPane().add(b);
frame.getConentPane().add(label);
frame.setSize(800,600);
frame.setVisible(true);
As it's an ArrayList you can use indexing. When the button is pressed increment the index and get the next item from the ArrayList.
Example
package items;
import java.util.List;
public class GetNextItem {
private static int itemIndex;
private List<String> itemList;
// Constructor with itemList
public GetNextItem(List<String> itemList) {
this.itemList = itemList;
itemIndex = 0; // start at the first item.
}
/**
* Get the current Item from the itemList
* #return the current item from the itemList or NULL if all the items are processed.
*/
public String getItem() {
if (itemIndex >= itemList.size()) {
return null; // end of list
}
return itemList.get(itemIndex);
}
/**
* Get the next Item from the itemList
* #return the next item from the itemList or NULL if all the items are processed.
*/
public String getNextItem() {
itemIndex ++;
return getItem();
}
}
Elements of an ArrayList can easily be accessed by index.
From a web page (built by JSP), you can request a specific question using a query parameter, e.g. showquestion.jsp?question=4.
The JSP-generated page can then include a button to show next question by generating a new link (Next) with the next higher index, as long as there are more questions.

sending a list of checked boxes from view to controller in play framework java

I have a view with the checkboxes
#for((jc)<-jobcategoryList) {
<input type="checkbox" name="jobcategory.id" value="#jc.id">#jc.name<br>
}
I just want to send this list of checked checkboxes to my controller.But on doing this
public class JobAdController extends Controller {
public static Result save() {
Form<Jobads> jobadsFormData = jobadsForm.bindFromRequest();
if (jobadsFormData.hasErrors()) {
System.out.println("Error in form");
return badRequest();
} else {
Jobads jads= jobadsFormData.get();
List<Jobcategories> jadsList= jads.getJobcategory();
System.out.print("\nLength is:"+jadsList.size());// always prints Length is:0
}}
}
where Jobads and Jobcategory are my models.
My Jabads.java model
public class Jobads extends Model {
#ManyToMany
private List<Jobcategories> jobcategories;
}
My problem is that whenever i submit my view form with the checkboxes(given above).My console prints Length is:0
When i tried to change my view to
#for((jc,index)<-jobcategoryList.zipWithIndex) {
<input type="checkbox" name="jobcategory[index]" value="#jc">#jc.name<br>
}
and submit my form the controller an [[NumberFormatException: For input string: "index"]] is generated on the first line of controller.
How can I send this checked boxes to my controller.
Thanks
Use:
#for(jc <- jobcategoryList) {
<input type="checkbox" name="jobcategories[]" value="#jc.id">#jc.name<br>
}
or
#for((jc,index) <- jobcategoryList.zipWithIndex) {
<input type="checkbox" name="jobcategories[#index]" value="#jc.id">#jc.name<br>
}
and in your form class:
public List<Long> jobcategories;

How to pass an ArrayList from Java class to jsp

Attempting to send an ArrayList from java class to servlet. The returned values of ResultSet is passed on to a model object and this object is added to an ArrayList. However I need retrieve this ArrayList in vieitems.jsp.
DBController.java
public void getAvailableItems(String sqlst) throws Exception {
Connection connection = getConnection();
Statement stm = connection.createStatement();
ResultSet rst = stm.executeQuery(sqlst);
ArrayList<Item> avitems = new ArrayList<Item>();
while (rst.next()) {
String itemname = rst.getString("ItemName");
String description = rst.getString("Description");
int qtyonhand = rst.getInt("QtyOnHand");
int reorderlevel = rst.getInt("ReorderLevel");
double unitprice = rst.getDouble("unitprice");
Item item = new Item(itemname, description, qtyonhand, reorderlevel, unitprice);
avitems.add(item);
}
//i need to send avitems to ViewItems.jsp
}
ViewItems.jsp
<form>
<Table border="1">
<tbody>
<tr> <td>Item Code</td><td>Item Name</td><td>Description</td><td> Qty On Hand</td><td>Reorder Level</td></tr>
//here i need to set the values of arraylist avitems
</tbody>
</Table>
</form>
In the servlet code, with the instruction request.setAttribute("itemList", avitems), you save your list in the request object, and use the name "itemList" for refering it.
When you arrive to your JSP, it's necessary to retrieve the list from the request, and for that you just need the request.getAttribute("itemList") method.
//Servlet page code DBController.java
request.setAttribute("itemList", avitems);
ServletContext context= getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("/ViewItems.jsp");
rd.forward(request, response);
// Jsp Page code ViewItems.jsp
<%
// retrieve your list from the request, with casting
ArrayList<Item> list = (ArrayList<Item>) request.getAttribute("itemList");
// print the information about every category of the list
for(Item item : list)
{
// do your work
}
%>
Make that ArrayList declaration static in DbController.java
In DbController create one method
void static ArrayList<items> getList()
{
return avitems;
}
it will return you the list in view.jsp
in view.jsp import DbController.java and add this scriplet
<%
ArrayList<Item> list = DbController.getList(); //it will return the list
%>
iterate and do whatever you want to do with this list in your view.jsp
i think this will help you.

how to display multiple values in select tag?

I want to display some name in the select tag but I am not able to do that.I have setter and getter of type string:
public void setFinalApprover(String finalApprover) {
this.finalApprover = finalApprover;
}
I am fetching data from database in the methodin DTOService Class like:
public List addApprover(EmpRegistrationForm leaveApplyForm){
List list=new ArrayList();
try {
con=DBConnection.getConnection();
String Approver="select emp_name from newemp_register where userType='employee'";
PreparedStatement pstmt=con.prepareStatement(Approver);
ResultSet rs=pstmt.executeQuery();
if(rs.next())
{
leaveApplyForm.setFirstApprover(rs.getString(1));
list.add(leaveApplyForm);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
My controller class is like:
#RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public ModelAndView showForm(#ModelAttribute("registerForm")EmpRegistrationForm EmpRegistrationForm, BindingResult result , ModelMap model,EmpRegistrationForm empRegistrationForm , HttpServletRequest request)
{
log.info("Inside Controller returning to loginform page....");
CommonDTOBean dtoBean=new CommonDTOBean();
EmpRegistrationForm registerForm = new EmpRegistrationForm();
model.put("registerForm", registerForm);
model.remove(registerForm);
EmpRegisterWorker worker=new EmpRegisterWorker();
List status=worker.addApprover(EmpRegistrationForm);
if(status!=null){
model.put("status", status);
}
}
and I am display values from list on jsp page like:
<tr><td><spring:message code="label.firstApprover"> </spring:message></td>
<td><form:select path="firstApprover" name="firstApprover">
<form:option value="">${status.firstApprover}</form:option>
now the problem here is,It is displaying only one value however resultset is returing multiple values.Please help me to solve this.
Is there any way to pass multiple values from DTOSerive class to controller and from controller back to jsp page?And for
String Approver="select emp_name from newemp_register where userType='employee'";if(rs.next())
{
leaveApplyForm.setFirstApprover(rs.getString(1));
list.add(leaveApplyForm);
} getting error like wrriting aborted to setFirstApprover.
Your Select tag should look like this. This should work.
<forms:select path="firstApprover" items="${status}" />
The content you want your select tag should filled up is referred using status property set in ModelMap.
<select name="firstApprover" >
<c:forEach items="${status}" var="stat">
<option value="${stat.your value}">
${country.your value}
</option>
</c:forEach>
</select>
In Select option tag value you can set your actual expected data with stat variable.
i.e. append your key with stat like my model key is name so i just append it like stat.name.

Spring form:select - multiple does not select first option by default

I have been working on a Spring project that makes use of the Spring form taglib (http://www.springframework.org/tags/form).
I am using some multiple select boxes to indicate some options (Country, factory,...)When I pass an entire list to the select - all is well: the first option of the select list is selected by default. However, when a user is from a specific country, the list is filtered and only his country is shown. In this case the first element is not selected by default.
JSP page:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:select path="countryValues" multiple="true" size="9" style="width:192px;" cssErrorClass="field-error">
<form:options items="${command.countries}" itemValue="countryCode" itemLabel="correctDisplayString"/>
</form:select>
Command.java
public List<CountryMaster> getCountries() {
return countries;
}
public void setCountries(List<CountryMaster> countries) {
this.countries = countries;
}
Controller.java
#RequestMapping(value = "/overview", method = RequestMethod.GET)
public String overview(HttpServletRequest request, Model model) {
Attrs attrs = getAttrs(request);
UserLocale.initUser(getUser(request));
User user = UserLocale.getUser();
List<FactoryMaster> factoryList = getFactoryList(attrs);
List<CountryMaster> countryList = getCountryList(attrs);
Command command = initCommand(attrs);
model.addAttribute(command);
if(user.hasRole(User.NORMAL)&& user.getCountryCode() != null){
if(countries == null){
countries= getDaoBuilder().getDaoCountry().countryMap();
}
String isoCode = countries.get(user
.getCountryCode());
List<CountryMaster> buffer = new ArrayList<CountryMaster>();
for(CountryMaster i : countryList){
if(isoCode.equalsIgnoreCase(i.getIsoCode())){
buffer.add(i);
}
}
System.out.println("List size: "+buffer.size());
command.setCountries(buffer);
}
else{
command.getCountries().addAll(getCountryList(attrs));
}
command.getModels().addAll(getModelList(attrs));
command.setBrands(getBrandList(attrs));
return "/reporting/overview";
}
private List<CountryMaster> getCountryList(Attrs attrs) {
List<CountryMaster> result = new ArrayList<CountryMaster>();
CountryMaster ct = new CountryMaster(CountryMaster.ISO_COUNTRY_JOKER, 00);
ct.setDescription("ALL");
result.add(ct);
result.addAll(attrs.countryList);
return result;
}
On the HTML page, I can see in other lists that the first element has the attribute selected="selected". Anybody have any idea why this is not the case when I manipulate my list? Or does anyone know what is resposible for this selected attribute allocation? (Is this javascript, java attribute,...?)
Thanks in advance!
Turns out the value of the listbox can be set: this piece of code made it quite an easy fix:
public String overview(HttpServletRequest request, Model model) {
Attrs attrs = getAttrs(request);
UserLocale.initUser(getUser(request));
User user = UserLocale.getUser();
List<FactoryMaster> factoryList = getFactoryList(attrs);
List<CountryMaster> countryList = getCountryList(attrs);
Command command = initCommand(attrs);
model.addAttribute(command);
if(user.hasRole(User.NORMAL)&& user.getCountryCode() != null){
if(countries == null){
countries= getDaoBuilder().getDaoCountry().countryMap();
}
String isoCode = countries.get(user
.getCountryCode());
List<CountryMaster> buffer = new ArrayList<CountryMaster>();
for(CountryMaster i : countryList){
if(isoCode.equalsIgnoreCase(i.getIsoCode())){
buffer.add(i);
}
}
System.out.println("List size: "+buffer.size());
command.setCountries(buffer);
// FIXED SELECTION OF ELEMENT
command.setFactoryValues(new String[]{isoCode});
// FIXED SELECTION OF ELEMENT
}
else{
command.getCountries().addAll(getCountryList(attrs));
}
command.getModels().addAll(getModelList(attrs));
command.setBrands(getBrandList(attrs));
return "/reporting/overview";
}
This way, you set the value of the listbox using code, and when the page is opened - the value is already there, making it selected by default.

Categories

Resources