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
Related
This is my arraylist for index 17
In this code may have data list or may not. Data is dispay when there are records. Not handled for no records
Java code:
//To avoid arrayindexoutofbound exception length checked
if (resultList.length >17) {
statisticsDetails.setqNames(resultList[17]);
//System.out.println(resultList[17]);
String[] qName=resultList[17].split("\\^");
List<StatisticsDetails> statisticsDetailsList = new ArrayList<StatisticsDetails>();
for (String queueName:qName ){
StatisticsDetails details = new StatisticsDetails();
String[] splitQueues = queueName.split("=");
details.setqKey(splitQueues[0]);
details.setqCount(splitQueues[1]);
statisticsDetailsList.add(details);
}
statisticsDetails.setqNamesList(statisticsDetailsList);
}
Jsp code:
<logic:iterate id="iteratorId" name="statistics.statisticsDetails" property="qNamesList">
<tr>
<td class="col-sm-6 col-md-6 col-lg-6"><bean:write name="iteratorId" property="qKey" /></td>
<td class="col-sm-6 col-md-6 col-lg-6"><bean:write name="iteratorId" property="qCount" /></td>
</tr>
</logic:iterate>
how to avoid arraybound error and JSP to handle when no data found
Use a null check using JSTL(Do not forget to import the tag library):
import core library:
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
and then use:
<c:if test="${not empty statistics.statisticsDetails}">
//keep your code here to iterate the list
</c:if>
Or use:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
and then:
<c:if test="${fn:length(statistics.statisticsDetails) > 0}">
//keep your code here to iterate the list
</c:if>
Please check all mapping is correct or not in the struts-config.xml. In my case, i found incorrect type was mentioned for form and then it was giving the error. Type means package name for the form. in tag.
I am developing a web application and I have a jsp page in which I have a table and few other things.All I want is to refresh the contents of table every 5 seconds.Below is my code of jsp page.Can anyone help me solve my problem.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.util.Calendar" %>
<%# page import="java.text.DateFormat" %>
<%# page import="java.util.Date" %>
<%# page import="java.text.SimpleDateFormat" %>
<HTML>
<HEAD>
<TITLE>Welcome to Crevavi </TITLE>
</HEAD>
<div style="width:950px; height:900; padding:10px; border:10px ridge black;">
<body bgcolor="white"; border="3px">
<img src="Crevavi_Plain.jpg" background-color="white" width="100" height="25" style=float:right;/>
<h1 style=margin-left:2px;><font size="5"> Crevavi Web Application</font></h1>
<hr color="black">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var auto = setInterval( function ()
{
$("#result").load("NewTable.html #result");
}, 5000); // refresh every 5000 milliseconds
</script>
//I want only the below division to refresh every 5 seconds.
<div id="result" style="width:930px; height:500; padding:5px; border:5px ridge black;">
<%
int rowCount = 0;
/*Calendar cal = Calendar.getInstance();
Date date1=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy,HH:mm:ss");
String formattedDate=dateFormat.format(date1);
System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
String[] values = formattedDate.split(",");
String date = values[0];
String time = values[1];*/
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/students","root","root");
Statement statement = connection.createStatement() ;
/* String sql = "INSERT INTO TEXTDATA (MachID,Date,Time,Text1,Text2,Text3,Text4,Text5,Text6,Text7,Text8,Text9,Text10,Text11,Text12) VALUES ('123','"+date+"','"+time+"','My','hello','thankyou','welcome','visit again','haha','good morning','sweet dreams','hi','hello','night','work')";
((java.sql.Statement) statement).executeUpdate(sql);*/
ResultSet resultset = statement.executeQuery("select * from textdata order by Date desc, Time desc");
while(resultset.next()){
rowCount++;
}
int firstrow = rowCount-10;
System.out.println(firstrow);
if(rowCount > 10){
resultset = statement.executeQuery("select * from textdata where Rowcount>'"+firstrow+"' order by Date desc, Time desc");
}else{
resultset = statement.executeQuery("select * from textdata order by Date desc, Time desc");
}
%>
<TABLE BORDER="1">
<TR>
<TH>Mach ID</TH>
<TH>Date</TH>
<TH>Time</TH>
<TH>Text1</TH>
<TH>Text2</TH>
<TH>Text3</TH>
<TH>Text4</TH>
<TH>Text5</TH>
<TH>Text6</TH>
<TH>Text7</TH>
<TH>Text8</TH>
<TH>Text9</TH>
<TH>Text10</TH>
<TH>Text11</TH>
<TH>Text12</TH>
</TR>
<% while(resultset.next()){ %>
<TR>
<TD> <%= resultset.getInt(1) %></td>
<TD> <%= resultset.getString(2) %></TD>
<TD> <%= resultset.getString(3) %></TD>
<TD> <%= resultset.getString(4) %></TD>
<TD> <%= resultset.getString(5) %></TD>
<TD> <%= resultset.getString(6) %></TD>
<TD> <%= resultset.getString(7) %></TD>
<TD> <%= resultset.getString(8) %></TD>
<TD> <%= resultset.getString(9) %></TD>
<TD> <%= resultset.getString(10) %></TD>
<TD> <%= resultset.getString(11) %></TD>
<TD> <%= resultset.getString(12) %></TD>
<TD> <%= resultset.getString(13) %></TD>
<TD> <%= resultset.getString(14) %></TD>
<TD> <%= resultset.getString(15) %></TD>
</TR>
<% } %>
</TABLE>
</div>
</br>
<form name = "Field_Details" action = "ServletApp" method= "get">
<fieldset style="float: center; width:900px; height: 75px;background-color:ivory; border-color:black;">
<font size = "2">Output Field :</font> <input type="text" name="Text1" maxlength="50" style="height:15px; width:100px; border-color:black"><font size = "2"></font>
<font size = "2"> MachId :</font> <input type="text" name="Text2" maxlength="15" style="height:15px; width:100px; border-color:black"><font size = "2"></font>
<font size = "2"> From Date(dd/mm/yy) :</font> <input type="text" name="Text3" maxlength="8" style="height:15px; width:100px; border-color:black"><font size = "2"></font>
<font size = "2"> To Date(dd/mm/yy) :</font> <input type="text" name="Text4" maxlength="8" style="height:15px; width:100px; border-color:black"><font size = "2"></font><br><br>
<input type= "submit" value="Send" style="height:30px; width:80px; margin-left:15px">
<input type= "submit" value="Search" style="height:30px; width:80px; margin-left:700px" onclick="form.action='FirstServlet';">
</BODY>
</HTML>
JSP is a server side technology, which means that if you want to refresh the page you will have to perform a request to the server which will return the new page. It is not possible to just return part of a page through normal JSP mechanisms.
If you want to just refresh the table you will need to use javascript to make an ajax call to the server to get the data you need, and repopulate the table with this data.
I altered code as below in my NewFile.jsp
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var auto = setInterval( function refresh()
{
$("#result").load("DemoFile.jsp");
}, 5000); // refresh every 5000 milliseconds
refresh();
</script>
then created new jsp file named DemoFile.jsp and copied part of code of NewFile.jsp division which I wanted to refresh.
I begun to learn datebase and servlet, JSP. And I don't know some fails. I can't see my db in JSP.
Java code:
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, login, password);
String sql = "select * fiz_phone";
Statement s = connection.createStatement();
s.executeQuery(sql);
rs = s.getResultSet();
while (rs.next()) {
dataList.add(rs.getInt("id"));
dataList.add(rs.getString("name"));
dataList.add(rs.getString("adress"));
dataList.add(rs.getString("phone"));
dataList.add(rs.getString("phone_adress"));
dataList.add(rs.getInt("cost"));
dataList.add(rs.getString("exempt_type"));
dataList.add(rs.getInt("exempt"));
dataList.add(rs.getString("date_claim"));
dataList.add(rs.getInt("number_claim"));
dataList.add(rs.getString("inspektor"));
dataList.add(rs.getString("date_repair"));
dataList.add(rs.getInt("phone_cost"));
dataList.add(rs.getString("call"));
}
rs.close();
s.close();
} catch (Exception e) {
System.out.println("Exception is ;" + e);
}
request.setAttribute("data", dataList);
RequestDispatcher dispatcher = request.getRequestDispatcher(page);
if (dispatcher != null) {
dispatcher.forward(request, response);
}
HTML:
<body>
<table border="1">
<tr>
<td ><b>ID</b></td>
<td ><b>Name</b></td>
<td ><b>Adress</b></td>
<td ><b>Phone</b></td>
<td ><b>Phone adress</b></td>
<td ><b>Cost</b></td>
<td ><b>Exempt type</b></td>
<td ><b>Exempt</b></td>
<td ><b>Date claim</b></td>
<td ><b>Number of claim</b></td>
<td ><b>Inspektor</b></td>
<td ><b>Date repair</b></td>
<td ><b>Phone cost</b></td>
<td ><b>Call</b></td>
</tr>
<%ArrayList<String> f = (ArrayList<String>) request
.getAttribute("data");
Iterator<String> itr = f.iterator();
while (itr.hasNext()) {%>
<tr id="tab">
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
<td ><%=itr.next()%></td>
</tr>
<%}%>
</table>
</body>
and servlet
<servlet>
<servlet-name>DataServlet</servlet-name>
<servlet-class>work_project.Data</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/DataServlet</url-pattern>
</servlet-mapping>
When I start this program, it give me this exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /DataPage.jsp at line 35
32: </tr>
33: <%Iterator itr;%>
34: <% List data= (List)request.getAttribute("data");
35: for (itr=data.iterator(); itr.hasNext(); ) {
36: %>
37: <tr>
38: <td ><%=itr.next()%></td>
I ran an example of your code. It worked. The only difference was that I inserted some code into the data list, instead of accessing a database. Even if the result set was empty, you should not be getting a null pointer exception.
Since you are getting a null pointer exception when you access the data list, it seems to indicate that the original list in the servlet was null. What is the code for instantiating the dataList in the servlet? Do you have a statement somewhere like
List<String> dataList = new ArrayList<String>();
Try debugging your code. Set a breakpoint in the servlet on the setAtribute statement. See if dataList is null.
Also check that the loop is executing. Be sure the result set is not empty.
Building on the answer of Roman C, the scriptlet scope is not the same as the expression language scope. If you use a jstl core template for the loop, then it should see row.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:forEach var="row" items="${data}">
<tr id="tab">
<td >${row.id}</td>
<td >${row.name}</td>
</tr>
</c:forEach>
I do not think this will resolve the original problem. data is probably still null.
Have you tried using the debugger and testing that dataList is not null when it is added to the request with setAttribute?
Responding to comment about debugger:
You need to step one more time, so that rows is initialized. Try the same thing in the servlet for the setAttribute statement, to see if dataList is null.
The code should be a valid SQL query by querying a database with JDBC statement.
String sql = "select * from fiz_phone";
It might be a typo but you ignored it in the code for the catch block
} catch (Exception e) {
//TODO you should handle the exception here
System.out.println("Exception is ;" + e);
}
Also since you are learning, you better return an object for each record from the resultset.
while (rs.next()) {
MyObject obj = new MyObject();
obj.setId(rs.getInt("id"));
obj.setName(rs.getString("name"));
...
dataList.add(obj);
}
Also do it in iterator
<%ArrayList<MyObject> f = (ArrayList<MyOobject>) request.getAttribute("data");
Iterator<MyObject> itr = f.iterator();
while (itr.hasNext()) {
MyObject obj = itr.next();
pageContext.setAttribute("row", obj);%>
<tr id="tab">
<td >${row.id}</td>
<td >$(row.name}</td>
...
</tr>
<%} pageContext.removeAttribute("row");%>
You should make MyObject a java bean (i.e. properties should have getters and setters). Latter you may try to remove scriptlets at all by using JSTL tag library and forEach tag.
I am trying to implement a simple dynamic dropdown menu in JSP.I am using MONGODB.Here is my code.But I am getting
<select name="village" id="village">
<option value="0">Select Village</option>
<%
BasicDBObject adminQuery = new BasicDBObject();
DBCursor cursor = villages.find(adminQuery);
while(cursor.hasNext()){
%>
<option value="<%= cursor.next().get("Village").toString()%>">
<%= cursor.next().get("Village").toString()%>
</option>
<% } %>
</select>
But I am getting following exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /home.jsp at line 116
113:
114: %>
115: <option value="<%= cursor.next().get("Village").toString()%>">
116: <%= cursor.next().get("Village").toString()%>
117: </option>
118: <% } %>
119: </select>
I don't know where is the problem.Please Help me
Use single quotes instead of double quotes.
Try this
<option value="<%= cursor.next().get('Village').toString() %>" ><%= cursor.next().get('Village').toString() %></option>
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>