Display not null values in query in jsp - java

In this portion of the code:
try {
connection = DriverManager.getConnection(
connectionUrl + dbName, userId, password);
statement = connection.createStatement();
String sql = "SELECT text_pub, path_photo FROM publication,publier, consomateur WHERE publication.id_publication=publier.publication_id_publication AND publier.users_id_user=consomateur.code_bar AND consomateur.code_bar = "+idUser+" AND 'path_photo' IS NOT NULL AND 'text_pub' IS NOT NULL";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr bgcolor="#8FBC8F">
<td><%=resultSet.getString("text_pub")%></td>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130"></td>
<%}
%>
I'm trying to select two values from my table, some of the values can be null, for example I can have a value for my column text_pub and not have a value in my column path_photo and vice versa, so in case I have text_pub and don't have path_photo, I want to display only the text_pub, but the probleme is that the value of text_pub is displayed but also the value of path_photo which is null.
PS: I know that treatements like these are better done in servlets, but I really want to make it work in a jsp. Thank you.

Either add a IFNULL check to the sql query:
SELECT IFNULL(text_pub,DEFAULT("")), IFNULL(path_photo,DEFAULT("")) FROM publication,publier,...
or add a check for the return value of resultSet.getString(..)
String text = resultSet.getString("text_pub");
if (text==null) {
text = "";
}
Edit:
in case I have text_pub and don't have path_photo, I want to display
only the text_pub this answer doesn't cover this
<%
while (resultSet.next()) {
String pub = resultSet.getString("text_pub");
if (pub==null) {
pub = "";
}
String photo = resultSet.getString("path_photo");
%>
<tr bgcolor="#8FBC8F">
<td><%= pub %></td>
<%
if (photo!=null) {
%>
<td><img src="images/<%=photo%>" width="150" height="130"></td>
<%
}
}
%>

I know that treatements like these are better done in servlets, but I really want to make it work in a jsp.
You're wrong here. This kind of things are handled in JSP, not in servlet, since logic to present the contents in the view belongs to the View (JSP) and not to the Controller (Servlet). Since you're using scriptlets, you should use an if sentence to validate if you should display the image or not:
while (resultSet.next()) {
%>
<tr bgcolor="#8FBC8F">
<td><%=resultSet.getString("text_pub")%></td>
<td>
<%
if (resultSet.getString("path_photo") != null) {
%>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130">
<%
}
%>
</td>
</tr>
<%
}
%>
If you don't want to display anything if resultSet.getString("text_pub") is null:
while (resultSet.next()) {
if (resultSet.getString("text_pub") != null) {
%>
<tr bgcolor="#8FBC8F">
<td><%=resultSet.getString("text_pub")%></td>
<td>
<%
if (resultSet.getString("path_photo") != null) {
%>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130">
<%
}
%>
</td>
</tr>
<%
}
}
%>
If you happen to write the code in the right way and use a Servlet to handle the data retrieval from database, fill the data in a List<SomeEntity>, add this list into a request attribute (probably with name "photoList") and forward to the desired JSP, then you could use JSTL to control the flow of the image display:
<c:forEach items="${photoList}" var="photo">
<tr bgcolor="#8FBC8F">
<td>${photo.textPub}</td>
<td>
<c:if test="${not empty photo.pathPhoto}">
<img src="images/${photo.pathPhoto}" width="150" height="130">
</c:if>
</td>
</tr>
</c:forEach>

Related

Convert the scriplet part into java class

I want to covert the scriptlet part into java classes. Basically, there would be two classes consisting of the entity classes and the other class containing the method. The entity class contains all the table elements. My main motive is to convert the scriptlet part into JAVA class.Here is what I have so far:
<%#page import="java.sql.*"%>
<%#page import="connection.Dbconnect"%>
<%#page session="true" %>
<div id="page" class="container">
<div id="content">
<%
String user = session.getAttribute("username").toString();
ResultSet rs=null;
ResultSet rs1=null;
String s1,s2,s3,s4,s5,s6,s7;
try{
Connection con=Dbconnect.getconnection();
Statement st = con.createStatement();
Statement st2 = con.createStatement();
rs=st.executeQuery("select * from user where user_name = '"+user+"'");
if ( rs.next() ){
s1 = rs.getString(1);
s2 = rs.getString(2);
s3 = rs.getString(3);
s4 = rs.getString(4);
s5 = rs.getString(5);
s6 = rs.getString(6);
s7 = rs.getString(7);
%>
<div class="title">
<h2> <%=s4%> </h2>
<h2> My Issues</h2>
<span class="byline"><p><b>Assign Issues</b></p></span>
</div>
<div class= "spltable">
<table border-bottom=1 align=center style="text-align:center">
<thead>
<tr>
<th>Issue ID</th>
<th>Subject</th>
<th>Description</th>
<th>Department</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<%
rs1 = st2.executeQuery("select * from issue where user_id = '"+s5+"'");
while(rs1.next()){
%>
<tr>
<td><%= rs1.getString(1) %></td>
<td><%= rs1.getString(2) %></td>
<td align="justify"><%= rs1.getString(3) %></td>
<td><%= rs1.getString(10) %></td>
<td><%= rs1.getString(14) %></td>
<td><%= rs1.getString(7) %></td>
</tr>
<% } %>
</tbody>
</table>
</div>
</div>
</div>
</div>
<%
}
}
catch(Exception e) {
out.println(e.getMessage());
}
%>
It's not necessary spring MVC for that (and to learn Spring MVC would take much more time and maybe neither the case to use here, despite is good to build robust applications, not the case here for what I see.... ), you create the class containing the logic, then a Servlet class will pass the result set to the Jsp page, an example on how to pass data from the Servlet to the Jsp can be found here: https://www.geeksforgeeks.org/getattribute-passing-data-from-server-to-jsp/

How to pass a value from loop of JSP page to another JSP page?

I have recently started working with JSP and I am trying to pass rollno value from one page to another. However, it is always passing the last row rollno.
Below is my first JSP page from where I'm taking values and also feepay page where I retrieve those values. I have tried appending rollno to URL but that didn't work either.
Please help me with this.
<%
String id=session.getAttribute("rollno").toString();
int idd=Integer.parseInt(id);
%>
<table class="table table-striped">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NO</th>
<th>FEE</th>
<th>FEE PAID</th>
<th>FEE PENDING</th>
<th>PAY FEE</th>
</tr>
<% while(resultset.next()){ %>
<TR>
<TD> <%= resultset.getString(1) %></td>
<TD> <%= resultset.getString(2) %></TD><% String rollno=resultset.getString(2).toString(); %>
<TD><%= resultset.getString(3) %></TD>
<td><%= resultset.getString(4) %></td>
<td><%= resultset.getString(5) %></td>
<TD>Pay Fee</TD>
</TR>
<% } %>
</thead>
</table>
1st : your overwriting the session in while loop so only you always getting last row value .
2nd : Just pass it like query string get parameter like below
<TD><a href="feepaypage.jsp?rollno=<%=resultset.getString(2) %>" >Pay Fee</a></TD>
3rd : Access the get parameter like below
<%
String id=request.getParameter("rollno").toString();
int idd=Integer.parseInt(id);
%>

I want to display the quantity of the selected item of a drop down list in a textbox. The data is stored in database

The code for retrieving data from database into Drop Down List.
<%
DataSource data = new MysqlDataSource();
Connection con = data.getConnection("root","system");
System.out.println("Connected to MySQL");
PreparedStatement pre = con.prepareStatement("select * from library.booklist");
ResultSet result = pre.executeQuery();
%>
<tr>
<font color="black" size="5"> <td> Book List : </td> </font>
<td> <select name= "BookList" id="booklist" onchange="show()">
<option> - select - </option>
<%
while (result.next())
{
String name = result.getString("Book");
System.out.println("Output Done");
%>
<option value="<%=name%>"> <%=name%></option>
<%
}
%>
</select></td>
</tr>
<tr>
<%
/* my code for displaying quantity is below but it's not working. I am new to jsp, so don't know how to populate the textbox. */
String value = request.getParameter("BookList");
pre = con.prepareStatement("select Quantity from library.booklist where Book = ? ");
result = pre.executeQuery();
%>
<font color="black" size="5"><td> Quantity : </td>
<%
while (result.next())
{
int quantity = result.getInt("Quantity");
System.out.println("quantity dikha raha hai");
%>
<input name = "Quantity" type = "text" size = "25" readonly = "readonly" value = "<%=quantity%>"> <%=quantity%> </input>
<%
}
%>
</td>
</tr>
Edit
You need to pass your BookList parameter to your prepared statement:
String value = request.getParameter("BookList");
pre = con.prepareStatement("select Quantity from library.booklist where Book = ? ");
pre.setString(1, value); // <------
result = pre.executeQuery();
Otherwise your query does not know which Book to select.
Original
You haven't said what the actual problem is, but your HTML markup has problems that definitely aren't helping.
Don't use the <font> tag. It is not supported in
HTML5.
Your second <font> needs a closing </font>.
You have a closing </td> tag at the end with no opening <td>.
The <input> tag is a void element, meaning it does not accept content between opening and closing tags. Write it as <input type="text" name="Quantity" .../>
Clean up those things and your problem might be fixed, or at least more obvious.

How to call Java method in JSP?

I m working on school project and I need to display academic year,section and medium dynamically from database in jsp file in drop down format. I am fetching the database values from java class and trying call tat java method in jsp to display those values but I am not getting nething der and i dnt want write query in jsp file.. please help me guyz m trying from last 3 days...
my java class
public class EmpBean {
public java.util.List dataList(){
ArrayList list=new ArrayList();
try {
Class.forName("driver");
Connection con = DriverManager.getConnection("url", "user", "pwd");
Statement st = con.createStatement();
System.out.println("hiiiii");
ResultSet rs = st.executeQuery("select * from employee");
while(rs.next()){
list.add(rs.getString("name"));
list.add(rs.getString("address"));
list.add(rs.getString("contactNo"));
list.add(rs.getString("email"));
}
System.out.println(rs.getString("contactNo"));
}
catch(Exception e){}
return list;
}
}
and my jsp file:
<%#page language="java" import="java.util.*" %>
<html>
<body>
<table border="1" width="303">
<tr>
<td width="119"><b>Name</b></td>
</tr>
<%Iterator itr;%>
<%
EmpBean p = new EmpBean();
List list= (List) p.dataList();
%>
for (itr=list.iterator(); itr.hasNext(); ) {
%>
<tr>
<select name="" id="" style="width: 150px;"">
<option value="-1"><%=itr.next()%></option>
</select>
</tr>
<%
}
%>
</table>
</body>
</html>
Edit 1:
Error message:
> The server encountered an internal error () that prevented it from
> fulfilling this request. exception org.apache.jasper.JasperException:
> An exception occurred processing JSP page
> /Administrative/collectFees.jsp at line 93 90: <td colspan="4"><div
> id="fndiv"> 91: <%Iterator itr;%> 92: <% List data=
> (List)request.getAttribute("data"); 93: for (itr=data.iterator();
> itr.hasNext(); ){ 94: %> 95: <select name="year1" id="yr1"
> style="width: 150px;" onclick="showDetails()"> 96: <option
> value="-1">><%=itr.next()%></option> root cause
> java.lang.NullPointerException
Try
<%
java.util.List list = new EmpBean().dataList();
%>
To Itterate you can use
<select>
<%for(String txt : new EmpBean().dataList()){%>
<option><%=txt%></option>
<%}%>
</select>
It's good to stick to good coding conventions.
Suming up the below thread: "The use of scriptlets (those <% %> things) in JSP is indeed highly discouraged"
How to avoid Java code in JSP files?
<tr>
<td><select name="" id="" style="width: 150px;"">
<option value="-1"><%=itr.next()%></option>
</select></td>
</tr>
you forgot the td tag

Fetch contents of a row from HTML table using '<tr onclick=alertContents()>'

i fetched and displayed data as a table in html from mysql db using jsp and java now what i want is when a user clicks on the particular row then the data in that row should populate in 3 different tags
example if my table has this data
Name Place Mobile number
a abc 123
b def 234
c ghi 345
(The above table is fetched from mysql db)
if the user clicks on the 3rd Row then the data such as name place and mobile number should be displayed in 3 different tags as shown below
Name: c
Place: ghi
Mobile: 345
thanks in advance
Before i used to have a button on the right side of each row with the "Name"(if it is a row of c then the button has c) on it so i dressed the button by a pic using CSS.
here goes the code i used
<form action="Options2" method="post">
<table id="sorter" class="sortable" id="example" class="pretty">
<tr>
<th>Book Id</th>
<th>Title</th>
<th>Author</th>
<th>Category</th>
<th>Status</th>
<th>Owner</th>
<th>Borrow Date</th>
<th>Return Date</th>
<th>Requested By</th>
<th>Actions</th>
</tr>
<%
ArrayList rs=(ArrayList)request.getAttribute("news");
ListIterator itr=rs.listIterator();
int i=1;
while( itr.hasNext()){
%>
<tr>
<td><%=itr.next()%></td>
<% int Id = itr.nextIndex(); %>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<% int Id2 = itr.nextIndex(); %>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<%
String Bname=rs.get(Id).toString();
System.out.println(Bname);
String Stat=rs.get(Id2).toString();
System.out.println(Stat);
if(!Stat.equals("Not Availible"))
{
%>
<td>
<input class="buttonir" type="Submit" name="X" value="<%=Bname %>"></td>
</tr>
<%
}
}
%>
</table>
</form>
Try this:
$('table tr').click(function () {
var BookId = $(this).children('td:eq(0)').html();
var Title = $(this).children('td:eq(1)').html();
var Author = $(this).children('td:eq(2)').html();
$('div').html(
'Book Id: ' + BookId + '<br />' +
'Title: ' + Title + '<br />' +
'Author:' + Author + '<br />'
);
});
Demo: http://jsfiddle.net/UPxB9/1/
Compare it with your Code its almost same just few changes mentioned
Only following function is added in your code and two lines more which are highlighted out of code
Edit
Add following function in your (already working) javascript tag on this page or in a js file which you are using in this page
function displayRowData(yourRow)
{
var dv=document.getElementById('yourDivId');
dv.innerHTML="<br>Name : "+ yourRow.children[0].innerHTML";
dv.innerHTML += "<br>Place: "+yourRow.children[1].innerHTML";
dv.innerHTML += "<br>Name : "+yourRow.children[2].innerHTML";
}
<form action="Options2" method="post">
<table id="sorter" class="sortable" id="example" class="pretty">
<tr>
<th>Book Id</th>
<th>Title</th>
<th>Author</th>
<th>Category</th>
<th>Status</th>
<th>Owner</th>
<th>Borrow Date</th>
<th>Return Date</th>
<th>Requested By</th>
<th>Actions</th>
</tr>
<%
ArrayList rs=(ArrayList)request.getAttribute("news");
ListIterator itr=rs.listIterator();
int i=1;
while( itr.hasNext()){
%>
Following Line is just modified it was already in your code
<tr onclick='displayRowData(this)'>
<td><%=itr.next()%></td>
<% int Id = itr.nextIndex(); %>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<% int Id2 = itr.nextIndex(); %>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<%
String Bname=rs.get(Id).toString();
System.out.println(Bname);
String Stat=rs.get(Id2).toString();
System.out.println(Stat);
if(!Stat.equals("Not Availible"))
{
%>
<td>
<input class="buttonir" type="Submit" name="X" value="<%=Bname %>"></td>
</tr>
<%
}
}
%>
</table>
Following line is added to your code
<div id='yourDivId'></div>
</form>

Categories