Reputation: 112
i am using mvc struts framework in my web application.
i am displaying dynamic values from my database in jsp page using scrilets <% %>
its been bad practice doing that way but i followed links of how to do it without scriptlets but cant understand much ..i am using struts and i have action and bean class
this is my jsp page
<%@page import="java.sql.ResultSet"%>
<%@page import="com.pra.sql.SQLC"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<table align="left" width="346" border="0">
<tr><td align="center" colspan="2" style="font-size:20px;">Tests We Provide</td></tr>
<tr>
<th width="194" height="52" align="left" nowrap>Test Name</th>
<th width="142" align="left" nowrap>Test Fee</th>
</tr>
<%
String sql = "Select tname,tfee from addtest order by tname";
ResultSet rs = SQLC.getData(sql, null);
while (rs.next()) {
String testname = rs.getString("tname");
String testfee = rs.getString("tfee");
%>
<tr>
<td width="194" height="30" nowrap><%=testname%></td>
<td width="142" nowrap><%=testfee%></td>
</tr>
<%
}
%>
</table>
please tell me how i display testnames and fees by writing code in formbean and retreive each value one by one from bean to jsp .. please tell me how i can do this without using scriplets.. answer in steps would be really appreciated thank you :)
Upvotes: 1
Views: 4194
Reputation: 5210
Move you db reading code to action controller. It should read values you need from db and put it into request or model.
Than use jstl to output your values (in jsp):
<c:out value="${parameterFromRequest}"/>
Define bean:
public class MyBean {
private final String tName;
private final String tFee;
public MyBean(String tName, String tFee) {
this.tName = tName;
this.tFee = tFee;
}
public String getTName() {
return tName;
}
public String getTFee() {
return tFee;
}
}
Create collection in action controller:
String sql = "Select tname,tfee from addtest order by tname";
ResultSet rs = SQLC.getData(sql, null);
Collection<MyBean> myBeans = new ArrayList<MyBean>();
while (rs.next()) {
String testname = rs.getString("tname");
String testfee = rs.getString("tfee");
myBeans.add(new MyBean(testname, testfee));
}
request.setAttribute("myBeans", myBeans);
Access in jsp:
<c:forEach var="myBean" items="${myBeans}">
Name: <c:out value="${myBean.tName}"/>
Fee: <c:out value="${myBean.tFee}"/>
</c:forEach>
Upvotes: 1