how to break columns in a table using jdbc - java

I am making a simple table which stores product details from database using jdbc connection.
My table looks like this:
<table>
<td>
<img border="3"
src="image path" height="200" width="200" />
<p align="center"></p> // these tag contains specific product details from db
<p align="center"></p>
</td>
</table>
right now I'm getting each product details in particular column( i.e multiple column within single row), but my problem is that this row keeps on expanding , & I want this row(which consist of multiple columns) to automatically break let say after every 5 products.
In simple words i want to arrange my products details in 4 x n format just like in flipkart , as shown below:
http://www.flipkart.com/mobiles/android-phones~type/pr?sid=tyy,4io&otracker=hp_nmenu_sub_electronics_0_Android%20phones
you can see first product sony experia then lg then after samsung galaxy product, new row starts then again 4 products , then new row. In this way i need to show my products which are coming from database using jdbc connection.
Can anyone suggest me what's the best possible approach to achieve this. & Is there any option to break columns after 4th one & then start new row?
I am displaying database contents in jsp as shown below, just for demo:
<%
//1. Retrieve all products from database
//1a. Load the Driver
Class.forName("com.mysql.jdbc.Driver");
//1b. Get a connection to the database
Connection con = DriverManager.getConnection("url", "un", "pwd
PreparedStatement ps = con.prepareStatement("SELECT * FROM table");
//1d. Execute and retrieve our result
ResultSet rs = ps.executeQuery();
//2. Base on the results returned, construct a table
%>
</p>
<table border="0">
<%
if(rs.next()) {
rs.beforeFirst(); // for making sure you dont miss the first record.
while(rs.next())
{ // opening while loop brackets.
%>
<td>
<div style=""><img border="3"
src="<%=rs.getString("image") %>" height="200" width="200" /></div>
<p align="center"><%=rs.getString("title")%></p>
<p align="center"><%=rs.getString("price")%></p>
</td>
<%
} //closing while loop bracket
}
else {
//if no record is found, simply display a no record message
%>
Nothing.
<%
}
%>
</table>

Use <tr> tags to organize the table in rows. (That's what it stands for - *t*able *r*ow.)
Keep track of how many products (N) you've read from the database. If N is a multiple of 4 (n % 4 == 0), close the <tr> and start a new one.
So the result looks like:
<table>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</table>
UPDATE based on updated question:
Here's my tweak based on your code. I really do not advocate doing SQL calls (or really any non-presentation-layer code) from within a JSP, but that's a matter for a different question.
<%
//1. Retrieve all products from database
//1a. Load the Driver
Class.forName("com.mysql.jdbc.Driver");
//1b. Get a connection to the database
Connection con = DriverManager.getConnection("url", "un", "pwd
PreparedStatement ps = con.prepareStatement("SELECT * FROM table");
//1d. Execute and retrieve our result
ResultSet rs = ps.executeQuery();
//2. Base on the results returned, construct a table
%>
</p>
<table border="0">
<tr>
<%
int i = 0;
if(rs.next()) {
rs.beforeFirst(); // for making sure you dont miss the first record.
while(rs.next())
{ // opening while loop brackets.
%>
<td>
<div style=""><img border="3"
src="<%=rs.getString("image") %>" height="200" width="200" /></div>
<p align="center"><%=rs.getString("title")%></p>
<p align="center"><%=rs.getString("price")%></p>
</td>
<%
i++;
if ((i % 4) == 0) {
%>
</tr>
<%
}
if (!rs.isLast()) { // don't open a new row if this is the last result
%>
<tr>
<%
} // closing isLast check
%>
<%
} //closing while loop bracket
}
else {
//if no record is found, simply display a no record message
%>
Nothing.
<%
}
%>
</tr>
</table>
I don't really have the patience to correct the whitespacing here, and I haven't actually compiled this, but hopefully you get the gist.

Apart from the response from dcsohl, you can use a combination of <div> and <span> elements. A <div> element is a block element, that is, each <div> will be rendered in new line. <span> element is an inline element.
This should help you:
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>

Related

I want to give 'edit-link i.e <a>edit</a>' if ans column of table from database is null

I am retrieving answer from ans column by using jdbc and showing it into a jsp page in a form of a table, if ans column is null or empty then I have to give a user edit link, but if ans column has a value then I'm going to show answer but the problem is if-else condition is not working. Please help me to solve this, My code is given below:
<div class="table-responsive">
<table class="table center-aligned-table">
<thead>
<tr class="text-primary">
<th>Question No</th>
<th>Question Name</th>
<th>Answer:</th>
<th> </th>
<th> </th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<%
try{
int oopa=1;
//String nme=(String)session.getAttribute("vname7");
DbCon cc=new DbCon();
Connection onn=cc.fun();
Statement stt=onn.createStatement();
ResultSet r=stt.executeQuery("select ques,ans from postquestion;");
while(r.next()){
%>
<tr class="">
<td><center><%=oopa++%></center></td>
<td><%=r.getString(1)%></td>
<%
if(r.getString(2)==null)
{
%>
<td>Edit</td>
<%
}
else
{
%>
<td><%=r.getString(2)%></td>
<%
}
%>
<td> </td>
</tr>
<%
}
}
catch(Exception vjin){
System.out.println("I am vjin: "+vjin);
vjin.printStackTrace();
}
%>
</tbody>
</table>
</div>
You might get empty values from your results. So check if r.getString(2) is empty or not, null differs from empty value.
More over, JSP is just a view component, writing DAO code in JSP is not a good practice.
Thanks
You can check for null values using wasNull() method of ResultSet.For example like below :
<%
//getting value of column in "a"
String a = r.getString(2);
//checking if resultset return null i.e a is null then do below:
if(r.wasNull())
{
%>
<td>Edit</td>
<%
}
else
{
%>
<td><%=r.getString(2)%></td>
<%
}
%>

Unable to submit the form using while loop

This is my Code that retrieves information from database and displays it in Table with an addition button that will used to submit(add to fav) to another new table with that row values and id of the user Below code displaying all records correctly with in table and every row is wrapped inside a form with button so when i click on a Particular row button then Values of that row only should be passed to target page,But for each and every row only the first record values are passing...
<%pst = con.prepareStatement("select * from reg_faculty");
res = pst.executeQuery();
while(res.next()) {
String uname = res.getString(1);
String id = res.getString(2);
String branch = res.getString(5);
String subject = res.getString(4);
%>
<tr><td align="center"><b><%=uname%></b></td><td align="center"><b><%=branch%></b></td>
<td align="center"><b><%=subject%></b></td>
<input type="hidden" name="fac_id" value="<%=id%>">
<input type="hidden" name="std_id" value="<%=ht%>">
<input type="hidden" name="fac_name" value="<%=uname%>">
<td align="center"><img src="viewimagef.jsp?id=<%=id%>&type=<%="faculty"%> " alt="" width="100" height="60" /></td>
<td align="center"><input type="submit" value="Add"/></td>
</tr>
<%
}
%>
Target page where the selected row values should pass to database but for any row selected the first record values are passing
String std_id1=request.getParameter("std_id");
String fac_id2=request.getParameter("fac_id");
String name=request.getParameter("fac_name");
try{
pst=con.prepareStatement("select * from fav_faculty where std_id=? AND fac_id=?");
pst.setString(1, std_id1);
pst.setString(2, fac_id2);
res=pst.executeQuery();
boolean exists = false;
if(res.next()){
out.println("Faculty Already exist in your List");
out.println("Faculty: "+fac_id2+" Student Id: "+std_id1+" Name: "+name);
}else{
pst=con.prepareStatement("insert into fav_faculty values(?,?)");
pst.setString(1, std_id1);
pst.setString(2,fac_id2);
int j=pst.executeUpdate();
if(j>0){
out.println("You successfully added "+name+" to your Faculty List");
}
}
}catch (Exception e) {
out.println("Unable To Add");
}
the problem is in the submit buttons you are using, a submit button belongs to the whole form, a working scenario would be changing the value of the submit button to the faculty id but keeping the same name for all the submit buttons.
another and probably a better solution would be adding a checkbox instead of a submit buttons.
<tr><td align="center"><b><%=uname%></b></td><td align="center"><b><%=branch%></b></td>
<td align="center"><b><%=subject%></b></td>
<input type="hidden" name="fac_id" value="<%=id%>">
<input type="hidden" name="std_id" value="<%=ht%>">
<input type="hidden" name="fac_name" value="<%=uname%>">
<td align="center"><img src="viewimagef.jsp?id=<%=id%>&type=<%="faculty"%> " alt="" width="100" height="60" /></td>
<td align="center"><input type="ckeckbox" name="fac_id" value="<%=id%>">
</tr>
%><%-- end of the while loop --%>
<input type="submit" value="add all">
and in the target page
String allSelectedFacultyIds[]= request.getParameterValues("fac_id");
for (int i=0;i<allSelectedFacultyIds.length;i++)
{
pst=con.prepareStatement("select * from reg_faculty where id="+allSelectedFacultyIds[i]);
//now you have the name, id, ... so the rest of your code should apply with minor changes
}

automatic bill number generation in jsp

In my project I need to generate bill number automatically.
My database is mysql.
I am getting the default value 0 from the column 'bill_no' and increment that value. It's working fine, but my problem is it is incremented up to 10. After that it is not incremented.
What is the reason? please let me know,thanks
My code is:
<%
connection=DBCreation.getConnection();
Statement statement=connection.createStatement();
resultSet= statement.executeQuery("select max(diag_pt_bill_no_v) from diagnostics_details");
if(resultSet.next())
{
System.out.println(resultSet.getInt(1));
i=resultSet.getInt(1)+1;
}}catch(Exception e){
e.printStackTrace();
%>
<form action="diagnosticsinsert" method="post" name="form">
<table><tr>
<td><label class="red">Bill No </label><input type=text name="bno" placeholder="Bill No" size="17px" value="<%=i++%>"
</td></tr>
</table>
<td><button name="save" id="save" style="width: 80px; height: 30px;font-size: 15px;" value="Save" accesskey="S" onclick="getTotalTests()">Save</button>(Alt+s) </td>
</form>
check if any max value set to your text box....

how to display value in dropdown list depending on another dropdownlist using jsp?

I'm tying to bind the value to dropdownlist i.e named as subtype which is depending on another dropdownlist i.e named as type. Please tell me how I can do that.. I have given I following code which implement for binding the dropdownlist depending on another dropdownlist.
`<table>
<tr>
<td>
<label id="type">Chosen category : </label>
</td>
<td>
<% String getType=request.getParameter("id");
out.println("<h4>"+getType+" <a href='post free ads.jsp'>Change the
category</a> </h4>");
%>
</td>
</tr>
<tr>
<td>
<label id="typeselect">Select type : </label>
</td>
<td>
<select name="type">
<option value="none">Select</option>
<%
Connection conn = NewClass.getOracleConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select distinct company from admin.all_stuff
where stuff_type='"+getType+"' ");
while(rs.next()){
%>
<option value="<%=rs.getString(1)%>"><%=rs.getString(1)%></option>
<%
}
%>
</select>
</td>
</tr>
<tr>
<td> <label id="subtypeselect">Select Subtype : </label></td>
<td>
<select name="subtype">
<option value="none">Select</option>
<%
try
{ %>
<% String typeselected = request.getParameter("type");
Statement stmtmt = conn.createStatement();
ResultSet rse = stmtmt.executeQuery("Select model_no from admin.all_stuff
where stuff_type='"+getType+"' and company='"+typeselected+"' ");
while(rse.next()){
%>
<option value="<%=rse.getString(1)%>"><%=rse.getString(1)%></option>
<%
}
%>
<% }
catch(Exception e)
{
out.println(e.getMessage());
}
%>
}
</select>
</td>
</tr>
</table>`
You need AJAX for this to get it work.
Your jsp is compiled into a servlet and then delivered to your client. After that no more changes are possible.
You have to handle an onChange event on the first drop down box in HTML and then post an AJAX request to your server to send back the content for the second drop down box.
Easiest way to start with AJAX is to get some library for example jQuery
$.get('ajax/test.html', function(data) {
alert(data);
});
This code allow us to download from HTML page some content from URL 'ajax/test.html'.
Second argument is callback function. Variable data has content of page 'ajax/test.html'
More: http://api.jquery.com/jQuery.get/

Working with <div> tag in JSP for making the contents hidden or visible

I have written a javascript function.
function wellChecked(state) {
if (state)
{
wellDropDown.style.visibility = 'visible';
}
else
{
wellDropDown.style.visibility = 'hidden';
}
}
I have a checkbox after the Well Modification <td> as given below,
<tr>
<td>On Call</td>
<td><html:checkbox property="onCall"/></td>
<td>Well Modification</td>
<td><input type="checkbox" onclick="wellChecked(this.checked)" /></td>
</tr>
When that checkbox is clicked I want the drop down list given under the div id=wellDropDown to be displayed. Defaultly, if the check box is not clicked, the drop down should not be displayed.
<tr>
<td>Active</td>
<td><html:checkbox property="active"/></td>
<div id="wellDropDown" style="visibility:hidden;">
<td>
<html:select property="wellFormatId">
<html:option value="">(Select)</html:option>
<bean:define id="wellFormatColl" name="wellFormats" scope="request"/>
<logic:iterate id="wellFormats" name="wellFormatColl" indexId="index" type="com.astrazeneca.compis.data.WellFormatVO">
<% Long wellId = wellFormats.getWellFormatId();%>
<% String wellIdNo = wellId.toString(); %>
<html:option value="<%=wellIdNo%>">
<bean:write name="wellFormats" property="wellFormatName"/>
</html:option>
</logic:iterate>
</html:select>
</td>
</div>
</tr>
When I tried executing this code, I could see the drop down list getting displayed irrespective of the checkbox checked or not.
Where I have went wrong in this scenario? Please give ur suggestions or ways to implement my requirement.
Your HTML is invalid. You may not have a div enclose a td like this. Either make the td itself visible or invisible, or put the div inside the td, instead of putting it around the td.
Also, unless wellDropDown is a global JS variable, the code should be
document.getElementById("wellDropDown").style.visibility = 'visible';
with jquery you could do this :
<tr>
<td>On Call</td>
<td><html:checkbox property="onCall"/></td>
<td>Well Modification</td>
<td><input type="checkbox" id="myCheckBox" /></td>
</tr>
...
<script>
$('#myDropDown').click(
function () {
$("#wellDropDown").toggle();
});
);
</script>

Categories

Resources