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.
Related
Here is the HTML code:
<table class="textfont" cellspacing="0" cellpadding="0" width="100%" align="center" border="0">
<tbody>
<tr>
<td class="chl" width="20%">Batch ID</td><td class="ctext">d32654464bdb424396f6a91f2af29ecf</td>
</tr>
<tr>
<td class="chl" width="20%">ALM Server</td>
<td class="ctext"></td>
</tr>
<tr>
<td class="chl" width="20%">ALM Domain/Project</td>
<td class="ctext">EBUSINESS/STERLING</td>
</tr>
<tr>
<td class="chl" width="20%">TestSet URL</td>
<td class="ctext">almtestset://localhost</td>
</tr>
<tr>
<td class="chl" width="20%">Tests Executed</td>
<td class="ctext"><b>6</b></td>
</tr>
<tr>
<td class="chl" width="20%">Start Time</td>
<td class="ctext">08/31/2017 12:20:46 PM</td>
</tr>
<tr>
<td class="chl" width="20%">Finish Time</td>
<td class="ctext">08/31/2017 02:31:46 PM</td>
</tr>
<tr>
<td class="chl" width="20%">Total Duration</td>
<td class="ctext"><b>2h 11m </b></td>
</tr>
<tr>
<td class="chl" width="20%">Test Parameters</td>
<td class="ctext"><b>{"browser":"chrome","browser-version":"56","language":"english","country":"US"}</b></td>
</tr>
<tr>
<td class="chl" width="20%">Passed</td>
<td class="ctext" style="color:#269900"><b>0</b></td>
</tr>
<tr>
<td class="chl" width="20%">Failed</td>
<td class="ctext" style="color:#990000"><b>6</b></td>
</tr>
<tr>
<td class="chl" width="20%">Not Completed</td>
<td class="ctext" style="color: ##ff8000;"><b>0</b></td>
</tr>
<tr>
<td class="chl" width="20%">Test Pass %</td>
<td class="ctext" style="color:#990000;font-size:14px"><b>0.0%</b></td>
</tr>
</tbody>
And here is the xpath to get the table:
//td[text() = 'TestSet URL']/ancestor::table[1]
How can I get this table using jSoup? I've tried:
tableElements = doc.select("td:contains('TestSet URL')");
to get the child element, but that doesn't work and returns null. I need to find the table and put all the children into a map. Any help would be greatly appreciated!
The following code will parse your table into a map, this code is subject to a few assumptions:
This xpath //td[text() = 'TestSet URL']/ancestor::table[1] will find any table which contains the text "TestSet URL" anywhere in its body, this seems a little bit brittle but assuming it is sufficient for you the JSoup code in getTable() is functionally equiavalent to that xpath
The code below assumes that every row contains two cells with the first one being the key and the second one being the value, since you want to parse the table content to a map this assumption seems valid
The code below throws exceptions if the above assumptions are not met i.e. if the given HTML does not contain a table definition with "TestSet URL" embedded in its body or if there are more than two cells in any row within that table.
If those assumptions are invalid then the internals of getTable and parseTable will change but the general approach will remain valid.
public void parseTable() {
Document doc = Jsoup.parse(html);
// declare a holder to contain the 'mapped rows', this is a map based on the assumption that every row represents a discreet key:value pair
Map<String, String> asMap = new HashMap<>();
Element table = getTable(doc);
// now walk though the rows creating a map for each one
Elements rows = table.select("tr");
for (int i = 0; i < rows.size(); i++) {
Element row = rows.get(i);
Elements cols = row.select("td");
// expecting this table to consist of key:value pairs where the first cell is the key and the second cell is the value
if (cols.size() == 2) {
asMap.put(cols.get(0).text(), cols.get(1).text());
} else {
throw new RuntimeException(String.format("Cannot parse the table row: %s to a key:value pair because it contains %s cells!", row.text(), cols.size()));
}
}
System.out.println(asMap);
}
private Element getTable(Document doc) {
Elements tables = doc.select("table");
for (int i = 0; i < tables.size(); i++) {
// this xpath //td[text() = 'TestSet URL']/ancestor::table[1] will find the first table which contains the
// text "TestSet URL" anywhere in its body
// this crude evaluation is the JSoup equivalent of that xpath
if (tables.get(i).text().contains("TestSet URL")) {
return tables.get(i);
}
}
throw new RuntimeException("Cannot find a table element which contains 'TestSet URL'!");
}
For the HTML posted in your question, the above code will output:
{Finish Time=08/31/2017 02:31:46 PM, Passed=0, Test Parameters={"browser":"chrome","browser-version":"56","language":"english","country":"US"}, TestSet URL=almtestset://localhost, Failed=6, Test Pass %=0.0%, Not Completed=0, Start Time=08/31/2017 12:20:46 PM, Total Duration=2h 11m, Tests Executed=6, ALM Domain/Project=EBUSINESS/STERLING, Batch ID=d32654464bdb424396f6a91f2af29ecf, ALM Server=}
You have to remove those quotation marks to get the row with the text; just
tableElements = doc.select("td:contains(TestSet URL)");
but note with the above you are only selecting td elements which contain the text "TestSet URL". To select the whole table use
Element table = doc.select("table.textfont").first();
which means select table with class=textfont and to avoid selecting multiple tables which can have the same class value you have to specify which to choose, therefore: first().
To get all the tr elements:
Elements tableRows = doc.select("table.textfont tr");
for(Element e: tableRows)
System.out.println(e);
Creating two result sets in a Java class below & when return to the jsp page, access it below as such & then loop through the result sets to put data on the page fields.
Was working just fine with ojdbc14.jar, but now upgraded to ojdbc7.jar (for Oracle 12c) via myEclipse project. Getting a Closed Resultset: next error in the jsp page when access the first result set.
Any ideas or suggestions please with this upgrade being done?
I know I can use collections, etc., but trying to keep the code the same with this returned cursors result sets to be accessed in the jsp page. Thanks for any assistance.
jsp page:
<%
BCSData vBCS =
(BCSData)session.getAttribute("com.sherwin.barcodeshipping.bcsData");
%>
<TABLE class="data" >
<TR class="header">
<TD class="dataTxt"> Order Number </TD>
<TD class="dataTxt"> Rex </TD>
<TD class="dataTxt"> Size Code </TD>
<TD class="dataTxt"> Loc </TD>
<TD class="dataNbr"> Total Cartons </TD>
<TD class="dataNbr"> Total Pallets </TD>
<TD class="dataNbr"> Total Weight </TD>
<TD class="dataNbr"> Total Units </TD>
<TD class="dataNbr"> Order Units </TD>
<TD class="dataNbr"> Order Qty </TD>
</TR>
<%
while (vBCS.bolResultSet.next())
{
%>
<TR class="body">
<TD class="dataTxt"><%= vBCS.bolResultSet.getString(1) %> </TD>
<TD class="dataTxt"><%= vBCS.bolResultSet.getString(2) %> </TD>
<TD class="dataTxt"><%= vBCS.bolResultSet.getString(3) %> </TD>
<TD class="dataTxt"><%= vBCS.bolResultSet.getString(4) %> </TD>
<TD class="dataNbr"><%= vBCS.bolResultSet.getFloat(5) %> </TD>
<TD class="dataNbr"><%= vBCS.bolResultSet.getFloat(6) %> </TD>
<TD class="dataNbr"><%= vBCS.bolResultSet.getFloat(7) %> </TD>
<TD class="dataNbr"><%= vBCS.bolResultSet.getFloat(8) %> </TD>
<TD class="dataNbr"><%= vBCS.bolResultSet.getFloat(9) %> </TD>
<TD class="dataNbr"><%= vBCS.bolResultSet.getFloat(10) %> </TD>
</TR>
<%
}
%>
</TABLE>
<HR class="innerMed" >
<TABLE class="data">
<TR class="header">
<TD class="dataTxt"> WHS </TD>
<TD class="dataTxt"> Customer </TD>
<TD class="dataTxt"> Dock </TD>
<TD class="dataNbr"> Total Pallets </TD>
<TD class="dataNbr"> Total Weight </TD>
<TD class="dataNbr"> Total Units </TD>
</TR>
<%
while (vBCS.bolSummaryResultSet.next())
{
%>
<TR class="body">
<TD class="dataTxt"><%= vBCS.bolSummaryResultSet.getString(1)
%> </TD>
<TD class="dataTxt"><%= vBCS.bolSummaryResultSet.getString(2)
%> </TD>
<TD class="dataTxt"><%= vBCS.bolSummaryResultSet.getString(3)
%> </TD>
<TD class="dataNbr"><%= vBCS.bolSummaryResultSet.getFloat(4)
%> </TD>
<TD class="dataNbr"><%= vBCS.bolSummaryResultSet.getFloat(5)
%> </TD>
<TD class="dataNbr"><%= vBCS.bolSummaryResultSet.getFloat(6)
%> </TD>
</TR>
<%
} // while
%>
</TABLE>
Java class where the result sets were created and closed:
public ResultSet bolResultSet;
public ResultSet bolSummaryResultSet;
public Integer assignDock(String pDBSource, String pLoginID)
{
Integer vRetCode;
String vRetMsg;
Connection vConnection = null;
CallableStatement vCallStmt = null;
try
{
vConnection = DBConnection.getConnection(pDBSource, pLoginID);
//System.out.println("BCSData.java assignDock");
vCallStmt = vConnection.prepareCall
("BEGIN ship_door_assignment_pkg.assign_dock (?,?, ?,?,?,?,?,?, ?,?,?,?,?,?, ?, ?,?,?,?); END;");
vCallStmt.setString(1, plantCode);
vCallStmt.setString(2, dock);
vCallStmt.setString(3, p1.palLbl);
vCallStmt.setFloat(4, p1.cartonQty);
vCallStmt.setFloat(5, p1.palSize);
vCallStmt.setFloat(6, p1.drumGallons);
vCallStmt.setFloat(7, p1.drumGross);
vCallStmt.setFloat(8, p1.drumTare);
vCallStmt.setString(9, p2.palLbl);
vCallStmt.setFloat(10, p2.cartonQty);
vCallStmt.setFloat(11, p2.palSize);
vCallStmt.setFloat(12, p2.drumGallons);
vCallStmt.setFloat(13, p2.drumGross);
vCallStmt.setFloat(14, p2.drumTare);
vCallStmt.setString(15, printer);
vCallStmt.registerOutParameter(16, OracleTypes.NUMBER);
vCallStmt.registerOutParameter(17, OracleTypes.VARCHAR);
vCallStmt.registerOutParameter(18, OracleTypes.CURSOR);
vCallStmt.registerOutParameter(19, OracleTypes.CURSOR);
vCallStmt.execute();
vRetCode = vCallStmt.getInt(16);
vRetMsg = vCallStmt.getString(17);
if (vRetCode == 0)
{
bolSummaryResultSet = (ResultSet)vCallStmt.getObject(18);
bolResultSet = (ResultSet)vCallStmt.getObject(19);
}
else
{ errorMsg = vRetMsg;
}
}
catch (SQLException se)
{
throw new RuntimeException(se);
}
finally
{
DBConnection.closeCallableStatement(vCallStmt);
DBConnection.closeConnection(vConnection);
}
return vRetCode;
} //assignDock
It's a lifecycle problem. If you close the database connection, all related result sets are also closed. (There is no connection to the database anymore. Don't ask me why it worked before.)
So you have to change your code such that it follows this sequence:
Run stored procedure and retrieve cursor/result set
Execute JSP page
Close database connection
I couldn't find any information if the result set retrieved as an out parameter of the stored procedure lives on after the statement has been closed. I think so. If not, you also need to wait before you close the statement.
The problem is that ResultSet must be closed too, and normally before the close of the statement. That statement or the connection might close the result set. However there are flags to make the result used longer, and even separate types. However common practice is to shovel a ResultSet to some List, and use that.
Try this:
vCallStmt = vConnection.prepareCall("BEGIN ship_door_assignment_pkg.assign_dock"
+ "(?,?, ?,?,?,?,?,?, ?,?,?,?,?,?, ?, ?,?,?,?); END;",
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
The last option should work.
I have my controller method:
#RequestMapping(value = "/provide", method = RequestMethod.GET)
public String list(Model model) {
List<Questionare> provide = scs.getPending();
logger.info("Number of questionares: "+provide.size());
model.addAttribute("certDatas", provide);
return "ssl/provide";
}
I have added logger.info in order to check if my list is being correctly created. It is. My logger log info such as :
2014-07-04 09:46:04,118 INFO
[pl.test.QuestionareControler] Number of questionares: 163
Now I want to display those 163 object in my jsp page in form of table like this:
<c:if test="${not empty provide}">
<table class="grid" style="width: 850px;">
<tr>
<th style="width: 100px;">Name</th>
<th style="width: 100px;">Surname</th>
<th style="width: 100px;">email</th>
</tr>
<c:forEach var="person" items="${provide}">
<%
i++;
%>
<tr>
<td>${person.name}</td>
<td>${person.suername}</td>
<td>${person.smtp}</td>
</c:forEach>
</table>
</c:if>
However my jsp page does not show that table (I mean if condition is not met I suppose, because I do not even see table header)
Can anyone give me a hint what am I doing wrong?
Your model is called certDatas and not provide.
Try this:
<c:if test="${certDatas != null}">
Check out the JSP expression language here:
http://www.tutorialspoint.com/jsp/jsp_expression_language.htm
i want to select td.team in such way for 1st textview1 i want td.team (1st td.team ) and for 2nd textview i want (2nd td.team ) ... i am using list apdater
Elements info = dpc.select("td.team "); but it giving me both team it 1st and 2nd so how i can do it .. pl tell me what Elements shld u use to get info
<tr class="odd">
<td class="date">10</td>
<td class="team">one</td>
<td class="team">two</td>
<td class="type">8M</td>
</tr>
<tr class="even">
<td class="date">01</td>
<td class="team">Nice</td>
<td class="team">Monaco</td>
<td class="type">€ 4.1M</td>
</tr>
<tr class="odd">
<td class="date">07</td>
<td class="team">thre</td>
<td class="team">fou</td>
<td class="type"> 600K</td>
</tr>
<tr class="even">
<td class="date">99</td>
<td class="team"><a href="sad" title="Marsala">M/a></td>
<td class="team">a</td>
<td class="type">50K</td>
</tr>
i really don't understand your question. Do u want to get the first td from each row and second td from each row. If thats is the case you need to form an array.
Elements info = dpc.select("tr.odd,tr.even").select("td.team");
int i = 0;
String linkText = "";
String cse_id = null ;
ArrayList<String> s =new ArrayList<String>();
for(Element el : info ){
linkText = el.attr("href");//or el.attr("title")
s.add(linkText);
System.out.println(linkText);/or print it
}
}
There might be some errors in the code i didn't test it .
'Select' method returns a 'Elements' object. This class has a method called 'get(int index)' which returns the i-th element in the selection, starting from zero.
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