java - How to retrieve data from a database from a jsp file? -
i have .jsp file displays info database. database class defined separately in .java file. contents of database calling getdata method of database. function calls made never execute , nil returned.
however if homecoming pre-computed values getdata function, executes fine.
i want know how can access database .jsp file.
i don't want add together java code straight .jsp file. want via method call. function .jsp file:
<% arraylist<string> al = com.database.getdata(); %>
java function:
getdata(){ al = new arraylist<string>(); connection conn = null; statement stmt = null; resultset rs = null; al.add("first"); try{ class.forname("com.mysql.jdbc.driver"); conn = drivermanager.getconnection(db_url,user,pass); stmt = conn.createstatement(); string sql = "select rs database"; rs = stmt.executequery(sql); while(rs.next()){ string str = rs.getstring("str"); al.add(str); } }catch(exception e){ e.printstacktrace(); } al.add("nikunj "); al.add("banka "); homecoming al; }
the contents of arraylist after phone call {"first", "nikunj", "banka"} , no info database.
how can info database. have tried creating static block populate arraylist @ start of programme not working.
there several ways this. can utilize jstl if want avoid java code in jsp. e.g.:
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %> <sql:setdatasource var="datasource" driver="com.mysql.jdbc.driver" url="jdbc:mysql://localhost/test" user="root" password="pass123"/> <html> <head> <title>jstl sql</title> </head> <body> <sql:query var = "result" datasource="${datasource}"> select str table </sql:query> <table border=1> <c:foreach var="row" query="${result.rows}"> <tr> <td><c:out value="${row.str}"/></td> </tr> </c:foreach> </table> </body> </html>
maybe want read:
how avoid java code in jsp-files? jsp using mvc , jdbc design patterns web based applications java jsp jdbc
No comments:
Post a Comment