How to display ArrayList items from java in jsp? - java

I have generated an Arraylist, where I get items from database row by row. I want to display the values in jsp, but I don't know how to bind jsp to java.
In java class, listBook is an Arraylist of type BookBean.
BookDao class:
public ArrayList<BookBean> listBooks = new ArrayList<>();
....
System.out.println(listBooks.get(0).getId()); ->display id of first row
System.out.println(listBooks.get(0).getTitle()); ->display title of first row
System.out.println(listBooks.get(0).getAuthor());
In my Controller class, i have:
public String showBooks(Model bookModel){
bookModel.addAttribute("bookAttribute", new BookDao());
return "book-list";
}
I want to print the results of listBook in jsp by using the Model from the Controller. How can I do that?
BookDao:
public ArrayList<BookBean> listBooks = new ArrayList<>();
public void generateBookList() {
try {
Connection connection = ConnectToDatabase.createConnection();
if (connection != null) {
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from book ");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
BookBean bookBean = new BookBean(resultSet.getInt("id_book"), resultSet.getString("title"), resultSet.getString("author"), resultSet.getString("publishDate"), resultSet.getInt("quantity"), resultSet.getString("bookPrice"));
listBooks.add(bookBean);
} }
} catch (Exception e) {
e.printStackTrace();
}}
BookController to open the jsp page "book-list.jsp":
#Controller
public class BookController {
#RequestMapping("/showBooks")
public String showBooks(Model bookModel){
bookModel.addAttribute("bookAttribute", new BookDao());
return "book/book-list";
}
}
I want to access the "listBooks" in jsp trough the Model created in the controller. I was thinking of jstl, but I cannot manage to write the code accordingly.

You can use jstl core tag <c:forEach>. If you need loop over your list you can do something like this:
In your BookController pass your list to the model:
model.addAttribute("bookList", yourList);
In JSP:
...
<c:forEach items="${bookList}" var="book">
${book.id} <%-- BookBean fields that you want print out--%>
${book.title}
<%-- another fields --%>
</c:forEach>
...
see official oracle documentation for more detail

On a JSP page simply do the following:
<%
out.println(listBooks.get(0).getId()); ->display id of first row
out.println(listBooks.get(0).getTitle()); ->display title of first row
out.println(listBooks.get(0).getAuthor());
%>

Related

How to call action after selecting values from dynamically created dropdown list using struts2

Here I have created dynamic dropdown list using this link, but when I select some value from available list it should be called in action class.
The dropdown list which can be seen in the image ,here the values are loaded dynamically from the database and now what I want is when I select any value from that two dropdown list that values (I mean text value) should be sent to the action class and there I will execute one JDBC select query on the basis of this two values and will display in the table shown in the image but everything should be on load.Action should be on selecting values from dropdown list not on any button click .With static values I am able to call value from dropdown list into action class with name attribute.But in this case I cannot :(
I hope I am clear now .
I have tried calling select tag using listkey,name and id but none of them worked .
Below is my JSP code:
<div>
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:form action="ActionSelect">
<s:submit value=" Click Here"/>
</s:form>
<div>
Action class for loading dynamic dropdown list :
package com.ca.actions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.ca.database.Database;
import com.ca.pojo.Event;
import java.sql.PreparedStatement;
import com.opensymphony.xwork2.ActionSupport;
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
List<Event> dataForBillsJspList;
private List state = new ArrayList();
private List status = new ArrayList();
String eventName;
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public RetrieveEvNaCoNaAction() {
// TODO Auto-generated constructor stub
}
public List<Event> getDataForBillsJspList() {
return dataForBillsJspList;
}
public void setDataForBillsJspList(List<Event> dataForBillsJspList) {
this.dataForBillsJspList = dataForBillsJspList;
}
public List getStatus() {
return status;
}
public void setStatus(List status) {
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_NAME,COMPANY_NAME,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo FROM EVENT");
ResultSet rs = ps.executeQuery();
//dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
/*dataForBillsJspList.add(new Event(rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo")));
System.out.println(rs.getString("EVENT_NAME"));*/
status.add(rs.getString("COMPANY_NAME"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
}
public List getState() {
return state;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
setState(this.state);
setStatus(this.status);
return "success";
}
public String showEventDetails(){
System.out.println("Hi.."+eventName);
return SUCCESS;
}
public void setState(List state) {
//implement the application specific logic to
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_ID,EVENT_NAME,COMPANY_NAME,CONTACT_PERSON,CONTACT_NO,EMAIL_ID,EVENT_VENUE,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME FROM EVENT");
ResultSet rs = ps.executeQuery();
dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"),rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),rs.getString("EVENT_VENUE"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo"),rs.getString("EVENT_TIME")));
//System.out.println(rs.getString("EVENT_NAME"));
state.add(rs.getString("EVENT_NAME"));
System.out.println(rs.getString("EVENT_ID"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
//Here for displaying the data on UI, we are using few hardcoded values//
}
}
After loading dynamic dropdown list now i am trying to call selected value in action class by S.O.P but it gives null pointer exception. Below is my POJO class:
package com.ca.pojo;
public class Dropdown
{
private String eventState;
private String companyState;
public Dropdown() {
// TODO Auto-generated constructor stub
}
public String getEventState() {
return eventState;
}
public void setEventState(String eventState) {
this.eventState = eventState;
}
public String getCompanyState() {
return companyState;
}
public void setCompanyState(String companyState) {
this.companyState = companyState;
}
}
and below is action class where I am trying to call that selected value by using name attribute :
package com.ca.actions;
import com.ca.pojo.Dropdown;
import com.opensymphony.xwork2.ActionSupport;
public class DropdownAction extends ActionSupport
{
Dropdown dp;
public DropdownAction() {
// TODO Auto-generated constructor stub
}
public Dropdown getDp() {
return dp;
}
public void setDp(Dropdown dp) {
this.dp = dp;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println(dp.getEventState());
return "success";
}
}
struts.xml is properly configured. Now after selecting two values I want to display data in the below table accordingly without any button click but in jsp i have created button just to see whether i am getting the selected value in action class but in actual i want it without any button click.
Well, there is a huge mess here :D
First of all, the NullPointerException is thrown because the values are not sent, and the values are not sent because they're not in the form.
You should enclose them in the form like this for them to be sent to the ActionSelect action:
<s:form action="ActionSelect">
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:submit value=" Click Here"/>
</s:form>
Solved the mistery, this doesn't solve your problem, though.
You have two main ways to contact actions from a page:
Using a standard submit (as you're doing):
you either submit a form with its content, or call a link by eventually passing parameters in the querystring. This creates a Request, that will contact an action, that will return an entire JSP, that will be loaded in place of the page you're on now.
Using AJAX:
you POST or GET to an action without changing the current page, and the action can return anything, like a JSP snippet, a JSON result, a binary result (through the Struts2 Stream result), etc...
You then can choose what to do with the returned data, for example load it inside a <div> that before was empty, or had different content.
Now your problem is that you're contacting an action that is not the one you're coming from (is not able to re-render the entire JSP you're on) and you're calling it without using AJAX, then whatever the object mapped to the "success" result is (the whole JSP, or a JSP snippet), it will be loaded in place of the JSP you're on, and it will fail.
Since you seem to be quite new to this, I suggest you start with the easy solution (without AJAX), and after being expert with it, the next time try with AJAX.
That said,
avoid putting logic in getters and setters;
avoid calling methods that are not setter as setters (setState, setStatus...);
always make your attributes private;
try giving speaking names to variables: state and status for event states and company states are really confusing; and what about "state" instead of "name" (in jsp and on DB is "name");
consider loading informations like selectbox content in a prepare() method, so they will be available also in case of errors;
you're not closing the connections (and BTW it would be better to use something more evoluted, like Spring JDBC, or better Hibernate, or even better JPA, but for now keep going with the raw queries)
The following is a refactoring of your code to make it achieve the goal. I'll use #Getter and #Setter only for syntactic sugar (they're Lombok annotations, but you keep using your getters and setters, it's just for clarity):
<head>
<script>
$(function(){
$("#event, #company").on('change',function(){
$("#myForm").submit();
});
});
</script>
</head>
<body>
<form id="myForm">
<div>
...
<s:select id="event" name="event" list="events" />
...
<s:select id="company" name="company" list="companies" />
...
</div>
</form>
<div>
...
Table - iterate **dataForBillsJspList** here
...
</div>
</body>
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
#Getter private List<Event> dataForBillsJspList = new ArrayList<Event>();
#Getter private List<String> events = new ArrayList<String>();
#Getter private List<String> companies = new ArrayList<String>();
#Getter #Setter private String event = null;
#Getter #Setter private String company = null;
#Override
public void prepare() throws Exception {
Connection con;
try {
con = new Database().Get_Connection();
// load companies
PreparedStatement ps = con.prepareStatement("SELECT DISTINCT company_name FROM event");
ResultSet rs = ps.executeQuery();
while (rs.next()) { companies.add(rs.getString("company_name")); }
// load events
ps = con.prepareStatement("SELECT DISTINCT event_name FROM event");
rs = ps.executeQuery();
while (rs.next()) { events.add(rs.getString("event_name")); }
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
}
#Override
public String execute() {
Connection con;
try {
con = new Database().Get_Connection();
// load the table. The first time the table is loaded completely
String sql = "SELECT EVENT_ID, EVENT_NAME, COMPANY_NAME, CONTACT_PERSON, CONTACT_NO, EMAIL_ID, EVENT_VENUE, " +
"date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom, date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME " +
"FROM event";
String where = "";
// if instead this action has been called from the JSP page,
// the result is filtered on event and company:
if (event!=null && company!=null) {
where = " WHERE event_name = ? AND company_name = ?";
}
// load companies
PreparedStatement ps = con.prepareStatement(sql + where);
if (where.length()>0) {
ps.setString(1,event);
ps.setString(2,company);
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),rs.getString("COMPANY_NAME"),
rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),
rs.getString("EVENT_VENUE"), rs.getString("dateAsFrom"), rs.getString("dateAsTo"),
rs.getString("EVENT_TIME")));
}
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
return SUCCESS;
}
}
It is a kickoff example, but it should work.
The next steps are:
create a POJO with id and description, show the description in the select boxes, but send the id
use header values ("please choose an event"...) and handle in action conditional WHERE (only company, only event, both)
PAGINATION
Good luck
Using Javascript/jQuery you can do this, it depends on what you want to do after reached action class.
If you want to navigate to another page use the code below.
Add onchange event as an attribute to your dropdown,
onchange="customFunction(this.value)"
create customFunction in header part,
function customFunction(selectedValue){
window.location="Action_URL?myValue="+selectedValue;
}
Or if you want to return back the same page use jQuery ajax,
$("#eventName").change(function(e){
var selectedValue = $(this).val();
$.ajax({
type : 'post',
url : 'Action_URL',
data: { myValue: selectedValue},
success : function(data) {
alert(data);
console.log(data);
}
});
});
Hope this helps.

Servlet with jdbc response to client [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
I have a database with houses, and HTML page with <SELECT>, where user need to select a district where the houses are located.
Servlet:
#WebServlet("/post")
public class HosesBaseServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
//choice from html form
String choice = request.getParameter("district");
//Database parameters
final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb2";
final String DB_USER = "root";
final String DB_PASSWORD = "root";
Connection conn;
try {
conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
System.out.println("Connection available");
PreparedStatement ps = conn.prepareStatement("SELECT Square, RoomNumbers, Price FROM houses WHERE District = " + choice);
}catch (SQLException ex) {
System.out.println("Fail to connect with base");
}
}
}
How can I put SQL select results into HTML page and give it back to client?
I created class House
public class Hosue implements Serializable {
private String price;
private String square;
private String RoomNumbers;
public String getPrice() {
return price;
}
public String getSquare() {
return square;}
public String getRoomNumbers() {
return RoomNumbers;}
public void setPrice(String price) {
this.price = price;
}
public void setSquare(String square) {
this.square = square;
}
public void setRoomNumbers(String roomNumbers) {
RoomNumbers = roomNumbers;
}
}
and houses
public class Houses {
public List<House> getList() {
}
}
and add script to my html. What next, how to add information from select to this list?
You can solve your problem as said by Jeed in the previous answer. However, it would be better if you model your db entities with Java objects and use them to encapsulate information from and towards the db. You may also use the DAO programming pattern to better organize your code, thus you can define simple objects (beans) to model data (your database entities) and data access object (DAO object) in which you would encode interaction with the db (your jdbc code).
Then you will have something like this to query your db (this code will be in your servlet):
HouseDAO h=new HouseDAO(db connection param...)
ArrayList<House> list=h.selectHouses();
In the HouseDAO object you will create a method selectHouse in which you will basically move the jdbc code you have in your servlet right now. By the way, your are missing a part in which you call the method execute query from the ps object. This method returns a ResultSet object which contains the query result.
With the code above, you will have your data in the ArrayList list, and you can use the code suggested by Jeed to output it.
Clearly, if you want to avoid using jsp, you can print your html code directly in your servlet. I do not recommend this as you would merge view details with control and model code. This is not good especially if you are planning to change your view in the future.
Add result of your query to some List or custom object and set it as attribute in your request object.
request.setAttribute("result", result);
and then forward to your next page using RequestDispatcher.
Use Gson external Library for sending java-List into String form to
HTML,
Your Servlet Code looks likewise,
List<House> listofHouses = getList from Database;
Gson gson = new Gson();
String json_obj = gson.toJson(listofHouses);
response.getWriter().println(json_obj);
Your HTML(use Jquery-ajax for Handling result & send Request to
Servlet ) Code looks some what nearer likewise......
<script>
$.ajax({
url: 'Servlet.do?distinct=YOUR_SELECTED_district_NAME',
type: "POST/GET",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
var returnedData = JSON.parse(data);
alert(data);
$.each(data, function(index, value) {
('#your_drop_down_tag_id').append($('<option>').text(value).attr('value', index));
});
}
});
</script>
NOTE: jquery-XXX.js file must be inclue into your project and into your html file properly.

getAttribute() returns null for drop down list in jsp

I am trying to pass value from database to drop down menu using getAttribute(). However, it returns null.
This is my jsp (updateLecturer.jsp) file:
<form action="updateLecturer" class="sky-form">
<header>Update Lecturer Information</header>
<center>
<fieldset>
<section>
<label class="select">
<select name="selectLecturer" id="lecturerFullname">
<option value="0" selected disabled>Lecturers Name</option>
**<option name="lecturerFullname"><%=((LecturerBean)request.getAttribute("LecturerFullname"))%></option>**
</select>
</label>
</section>
</center>
<footer>
<center><button type="submit" class="button">Update</button></center>
</footer>
</form>
This is my servlet UpdateLecturerServlet.java) :
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String lecturerFullname = request.getParameter("LecturerFullame");
LecturerBean lecturer = new LecturerBean();
lecturer.setLecturerFullname(lecturerFullname);
request.setAttribute("LecturerFullname",lecturerFullname);
RequestDispatcher view = getServletContext().getRequestDispatcher("/updateLecturer.jsp");
view.forward(request,response);
}
This is my UpdateLecturerDAO :
static Connection currentCon = null;
static ResultSet rs = null;
public static LecturerBean selectlecturer(LecturerBean Lbean) {
// preparing some objects for connection
System.out.println("JIJIJI");
Statement stmt = null;
String lecturerFullname = Lbean.getLecturerFullname();
System.out.println("j444444");
String searchQuery = "select lecturerfullname from lecturer";
System.out.println("Your lecturer is " + lecturerFullname);
System.out.println("Query: " + searchQuery);
try {
// connect to DB
currentCon = JavaConnectionDB.getConnection();
stmt = currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
// boolean more = rs.next();
while(rs.next())
{
LecturerBean lecturer = new LecturerBean();
lecturer.setLecturerFullname(rs.getString("LecturerFullname"));
lecturer.add(lecturer);
}
}
catch (Exception ex) {
System.out.println("Select failed: An Exception has occurred! " + ex);
}
PLEASEEEE HELP :( thank you very much
If you set some attribute in request like this
request.setAttribute("key",obj);
You can get it display in jsp by a scriplet like this
<%=request.getAttribute("key")%>
In your case please check the following points
Check whether the following code is giving you a null.
String lecturerFullname = request.getParameter("LecturerFullame");
If this gives you null then check whether your passing parameter LecturerFullame in url.
In the jsp please cast the following to correct object
<option name="lecturerFullname"><%=((String)request.getAttribute("LecturerFullname"))%></option>
And let me know.
I've never worked with any of this type of code before, so I'm not sure how the attribute system works, but I noticed an anomaly in your code:
Where you are setting:
request.setAttribute("LecturerFullname",lecturerFullname);
Where you are getting:
lecturer.setLecturerFullname(request.getAttribute("lecturerFullname",lecturer));
Notice it yet? Where you are setting it, you put a capital "L" and I believe it's case sensitive. Doesn't hurt to try.
In UpdateLecturerServlet.java.
//calling selectlecturer() to retrieve list full names and store it in session
request.setAttribute("LecturerFullname",selectlecturer());
RequestDispatcher view = getServletContext().getRequestDispatcher("/updateLecturer.jsp");
view.forward(request,response);
Now selectlecturer() method.
public static List<LecturerBean> selectlecturer() {
//DB query to retrieve all lecturer fullnames
List<LecturerBean> lecturers = new ArrayList<LecturerBean>();
while(rs.next())
{
LecturerBean lecturer = new LecturerBean();
lecturer.setLecturerFullname(rs.getString("LecturerFullname"));
lecturers.add(lecturer);
}
return lecturers;//return the list lecturer fullnames
}
In updateLecturer.jsp.
<%
java.util.List<LecturerBean> lists = (java.util.List<LecturerBean>)request.getAttribute("LecturerFullname"));
for(LecturerBean bean:lists)
{
%>
<option name="lecturerFullname"><%=bean.getLecturerFullname()%></option>
<%
}
%>
But you should avoid Java code in JSP. Just for the reference here I'm giving this code.

How pass a List to JSP page without loading the JSP

I am using the Spring MVC framework ModelAndView method in controller to display a page. On the page, I have an element dropdown element and table. On selection of an option in the dropdown, I am passing the Id of the element to the controller and querying the results for the selected option. I am using Hibernate to fetch data from the db. So, the result is in the form a list of objects. I have to populate this result in the table.
The following code will display a JSP and pass a list reference to JSP. I am using that reference to populate options on the page.
Code:
List<String> users = new ArrayList<String>();
ObjectMapper objectmapper = new ObjectMapper();
String string = "";
ModelAndView model = new ModelAndView("xxxx");
containerList = mapper.writeValueAsString(users);
List<Intermediate> list = getIntermediateList();
model.addObject("IntermediateList" , List);
return model;
JSP code:
<td>Intermediate</td>
<td>
<select class="form-control margin" id = "dpd" >
<option value="0" selected>--Select--</option>
<c:forEach var="list" items="${IntermediateList}">
<option label="${list.name}" value="${item.id}"></option>
</c:forEach>
</select>
</td>
On select of an option from the dropdown, it will make a ajax call and pass the selected Id to the controller method:
Ajax call code:
$("#dpd").change(function(e){
var intermediate = $("#dpd").val();
var data = {
Intermediate : intermediate
};
$.ajax({
method : 'POST',
url : 'intermediateUsers',
data : data ,
success : function(result) {
alert("Success");
}
,
error : function(result) {
alert('An error occurred.');
}
});
Controller code for querying the list:
#RequestMapping("/intermediateUsers")
#ResponseBody
public List<Users> intermediateUsers(#RequestParam(value = "intermediate" ,required = false) String intermediate) {
List<Users> users = null;
int selection = Integer.parseInt(intermediate);
users = service.intermediateUsers(selection);
return users;
}
It is working fine to this point and I am able to get the list of users based on the selected option.
Please suggest how I may pass this list to the JSP, not by loading the entire page but by loading only the table element to populate the list. I tried many ways, like converting that list into a JSONObject, but nothing has worked.
You can use something like this
function showContacts(response){
$("#tableid tbody tr").remove();
$.each(response.contacts, function(i, contact) {
$("#tableid tbody").append(
$('<tr>').append($('<td>').text(contact.name),
$('<td>').text(contact.phoneNumber),
$('<td>').text(contact.address)
));
});
}
function loadContacts(){
$.ajax({
type: "GET",
url: "url/contacts",
success: function( response ){
showContacts(response);
}
});
}

How to retrieve Arraylist object in javascript/jsp?

I am developing one sample web application using JSP and Servlets, in this application i have set some object in the Servlets, i can retrieve that value in JSP by using request.getAttribute("Object"). Here i want to iterate that array of value in JSP. How can i achieve this any one help me.
My servlet code:
ArrayList<Performer> Performerobj=new ArrayList<Performer>();
ResultSet rst = stm1.executeQuery("some query");
while (rst.next())
{
Performer obj=new Performer();
obj.setProject(projectname);
obj.setCount(rst.getString("COUNT"));
obj.setDate(rst.getString("DATE"));
obj.setEmpid(rst.getString("empid"));
Performerobj.add(obj);
}
request.setAttribute("Performer", Performerobj);
Performer.java
public class Performer {
private String project;
private String empid;
private String date;
private String count;
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
/*setter and getter...... for all*/
Perform.jsp
<% List<Performer>obj1=List<Performer>)request.getAttribute("Performerobj"); %>
<script>
var obj=<%=obj1%>
for(obj object : list)
{
/*IS it correct way or how can i iterate*/
}
</script>
You can do that if you transform the ArrayList object into a JSON using a library like Jackson:
<% List<Performer>obj1 = (List<Performer>) request.getAttribute("Performerobj"); %>
<script>
var obj=<%=new ObjectMapper().writeValueAsString(obj1)%>;
for(obj object : list)
{
/*IS it correct way or how can i iterate*/
}
</script>
Another option is to use JSTL:
<c:forEach var="performer" items="${Performerobj}">
<c:out value="${performer.project}"/>
</c:forEach>

Categories