java web application mysql connection error - java

I am new in Java. My Java Environment is 1. Windows 8. 2. Mysql - 5.5.27. 3. Eclipse IDE for Java EE Devoper v-2. 5. Apache Tomcat v-7. 6. mysql-connector-java-5.1.28 bin rar 7. JDK 1.7. Now i want to connect with mysql from jsp file. I already add the mysql-connector to the library resource. But i can not connect. My code and error i given in the following.
Code: home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page language="java" import="java.sql.Connection"%>
<%# page language="java" import="java.sql.PreparedStatement"%>
<%# page language="java" import="java.sql.ResultSet"%>
<%# page language="java" import="java.sql.SQLException"%>
<%# page language="java" import="java.sql.DriverManager"%>
<%# page language="java" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bengal Contact List | Home </title>
</head>
<body>
<%
Connection con = null;
try {
//Class.forName("com.mysql.jdbc.Driver");
String driver="com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/java_contact";
String user = "root";
String password = "";
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
}
catch(ClassNotFoundException cnfe){
System.out.println(cnfe);
}
catch(SQLException ex){
System.out.println(ex);
}
// Connection con;
// con=DBConnect.GetDBConnect();
String sql="SELECT * FROM contactsinfo";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
%>
<table border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Designation</td>
</tr>
<%
while(rs.next()){
%>
<td><%=rs.getInt("ID")%></td>
<td><%=rs.getString("Name")%></td>
<td><%=rs.getString("Designation")%></td>
<%
}
%>
</table>
<h1>Now i am in Home Page.I want to show table information of Contact List.</h1>
</body>
</html>
Error:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:534)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
org.apache.jsp.home_jsp._jspService(home_jsp.java:96)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.12 logs.
please find out where is the problem.

try to give null checks for rs.getInt("ID"), rs.getString("Name"), rs.getString("Designation"). NullPointerException is throwing there in the page.
Use the same for con object too.

first check your result is empty or not
ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}
else{
<td><%=rs.getInt("ID")%></td>
<td><%=rs.getString("Name")%></td>
<td><%=rs.getString("Designation")%></td>
}

Firstly avoid using of scriptlets "<% %>" in JSP.
Secondly always do null check in your code, especially if you are using db result. You are heving null pointer exception in your JSP and it appear here;
<td><%=rs.getInt("ID")%></td>
<td><%=rs.getString("Name")%></td>
<td><%=rs.getString("Designation")%></td>
Please try sthg like that;
-put this top on the file;
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
and then
<c:if test="MAKE_YOUR_NULL_CHECK_HERE">
//Write your <td> here.
</c:if>

you must add port number of the Database(3306) port number, username and password and I have attached working code.. check and update the comment.....
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page language="java" import="java.sql.Connection"%>
<%# page language="java" import="java.sql.PreparedStatement"%>
<%# page language="java" import="java.sql.ResultSet"%>
<%# page language="java" import="java.sql.SQLException"%>
<%# page language="java" import="java.sql.DriverManager"%>
<%# page language="java" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bengal Contact List | Home </title>
</head>
<body>
<%
Connection con = null;
try {
//Class.forName("com.mysql.jdbc.Driver");
String driver="com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/schemaname";
String user = "username";
String password = "password";
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
}
catch(ClassNotFoundException cnfe){
System.out.println(cnfe);
}
catch(SQLException ex){
System.out.println(ex);
}
// Connection con;
// con=DBConnect.GetDBConnect();
String sql="SELECT * FROM contactsinfo";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
%>
<table border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Designation</td>
</tr>
<%
while(rs.next()){
%>
<td><%=rs.getInt("ID")%></td>
<td><%=rs.getString("Name")%></td>
<%
}
%>
</table>
<h1>Now i am in Home Page.I want to show table information of Contact List.</h1>
</body>
</html>

Related

Unable to retreive value from oracle database using JSP, getting java.sql.SQLException: Result set after last row

I have written simple jsp program where I am trying to retrieve username and password from database, here is my jsp program.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import ="java.sql.*" %>
<%# page import ="oracle.sql.*" %>
<%# page import ="oracle.jdbc.driver.*" %>
<%#page import="oracle.jdbc.driver.OracleDriver"%>
<%# page import ="java.util.Date" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String driver="oracle.jdbc.driver.OracleDriver";
String userid = request.getParameter("username");
String pwd=request.getParameter("password");
Connection con = null;
%>
<%try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:CCB25", "CISADM", "CISADM");
Statement st= con.createStatement();
String query="select * from CMLOGIN where USERID='"+userid+"'";
ResultSet rs=st.executeQuery(query);
String pass1="";
rs.next();
pass1 = rs.getString("password");
if(pass1.equals(pwd))
{
%>
<%String name=request.getParameter("username");
session.setAttribute("nam",name);%>
<jsp:forward page="admin.jsp"></jsp:forward>
<%}
else
{
String msg="Username or password failed";%>
<center> <p style="font-family:verdana;color:red;"><%=msg %>
<jsp:include page="Login.jsp"></jsp:include>
<%}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
and i have javax.servlet.jar and ojdbc7-12.1.0.2.jar in web-inf/lib folder. I am getting java.sql.SQLException: Result set after last row on the following line "pass1 = rs.getString("password");" Could you please guide me what I am doing wrong.
You first need to check if the ResultSet has any rows in it before calling .next(), in order to prevent this exception.
Use this:
if (rs.next){
//read next row
}
if you want to loop through all the rows of the ResultSet, use a while loop:
while(rs.next){
//do something for every row
}
Here is the same cleaned up a little. You'll have to add back in exception handling and closing of the connection/statement/resultset
Hopefully you never have to use this code for real as it's taking in a password from query string in clear then comparing to a clear version in the db.
Password comparison moved to the sql itself.
Always use PreparedStatements to avoid sql injection
Comments are in the code.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import ="java.sql.*" %>
<%# page import ="java.util.Date" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String userid = request.getParameter("username");
String pwd = request.getParameter("password");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE", "klrice", "klrice");
//
// USE BINDS ! to avoid sql injection
// push the userid and passwd comparison to the db
// no need to get the password and compare locally
//
String query = "select password from cmlogin where userid=? and password=?";
PreparedStatement st = con.prepareStatement(query);
//
// Binds in the vaules
//
st.setString(1,userid);
st.setString(2,pwd);
ResultSet rs = st.executeQuery();
String pass1;
// .next will advance if the query has any results
//
if ( rs.next() ) {
pass1 = rs.getString("password");
String name =request.getParameter("username");
session.setAttribute("nam",name);
%>
<jsp:forward page="admin.jsp"></jsp:forward>
<%
} else {
String msg="Username or password failed";
%>
<center> <p style="font-family:verdana;color:red;"> <%=msg %>
<jsp:include page="Login.jsp"></jsp:include>
<% } %>
</body>

Resultset rs cannot be resolved

very recently i started learning Java Technology right now I'm working on Servlets while i fetch the data from data base it's not resolving resultset rs
here I attached my code
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<script
type="text/javascript" language="javascript">
javascript:window.history.forward(1);
</script>
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
update
display
logout
<script>
<%
try{
ResultSet rs=null;
String mail=(String)session.getAttribute("mail");
String sql="select * from tempregister where mail=?";
Class.forName("com.ibm.db2.DB2Driver");
Connection con=DriverManager.getConnection("jdbc:db2://localhost:50000/TEMP", "tarun", "12347890");
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, mail);
rs=ps.executeQuery();
}catch(Exception e){
}
%>
<%
while(rs.next())
{
%>
<%=rs.getString(4)%>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
}%>
</script>
</a>
</body>
</html>
please help me out.. thanks
Your code should be changed at least:
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<script
type="text/javascript" language="javascript">
javascript:window.history.forward(1);
</script>
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
update
display
logout
<%
ResultSet rs = null;
try {
String mail = (String) session.getAttribute("mail");
String sql = "select * from tempregister where mail=?";
Class.forName("com.ibm.db2.DB2Driver");
Connection con = DriverManager.getConnection("jdbc:db2://localhost:50000/TEMP", "tarun", "12347890");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, mail);
rs = ps.executeQuery();
while (rs.next()) {
%>
<%=rs.getString(4)%>
<%
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>

jsp and getting attributes data

I am trying to display the note attribute that I saved into my request.setAttribute("entries", entries), but I can't access this data in my jsp and I can't figure it out. I've tried {note} , but that doesn't work.
This is my controller class:
while( rs.next() )
{
int id = rs.getInt("id");
String name = rs.getString("name");
String note = rs.getString("note");
String title = rs.getString("title");
Notes entry = new Notes(id, name, note, title);
entries.add(entry);
}
request.setAttribute("entries", entries);
request.getRequestDispatcher( "/WEB-INF/homework2/MyNotes.jsp" ).forward(
request, response );
}
catch( SQLException e )
{
throw new ServletException( e );
}
finally
{
try
{
if( c != null ) c.close();
}
catch( SQLException e )
{
throw new ServletException( e );
}
}
}
}
This is my jsp view:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>MyNotes</title>
</head>
<body>
<p align="right">Hello, ${sessionScope.CurrentUser}! Logout</p>
<span>JOT My Notes | New</span>
<br>
<br>
<br>
<p>${note} </p>
<p>${applicationScope.entries.note},</p>
</body>
</html>
You already have your List in your request so:
Get the list with EL language
Iterate it to get all objects inside.
Then you can, (for example) put info a table:
<c:forEach items="${requestScope.entries}" var="entry">
<tr>
<td>ID: <c:out value="${entry.id}"/></td>
<td>Name: <c:out value="${entry.name}"/></td>
<td>Note: <c:out value="${entry.note}"/></td>
<td>Title: <c:out value="${entry.title}"/></td>
</tr>
</c:forEach>

Access DB query not showing in Apache, here's the scriplet in Netbeans i have

This is what i have, when i run the jsp file on the browser the only thing i get is the "Report" header but not the query result, please guide me to the right way.
<%#page import="java.sql.ResultSet"%>
<%#page import="database.Dba"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<center> <h1> Report </h1></center>
<%
//scriplet
try{
Dba db =
new Dba(application.getRealPath("daw.mdb"));
db.conectar();
db.query.execute("select usuario from usuarios");
ResultSet rs = db.query.getResultSet();
while(rs.next()){
out.print(rs.getString(1)+ "<br>");
}
db.desconectar();
}catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>

how to retrieve multiple blob images from mysql using jsp [duplicate]

This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 6 years ago.
I am trying to retrieve few blob images from mysql database using java. Now , the problem is that I'm able to get only one image at a time, the other images are not getting displayed.
Below is my jsp code , where I'm doing this(just for demonstration purpose):
<?xml version="1.0" encoding="UTF-8" ?>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# page language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%# page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MindDotEditor posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex, nofollow" />
<link href="../sample.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="../fckeditor.gif" type="image/x-icon" />
</head>
<body>
<%
String url = "jdbc:mysql://localhost:3306/grandsho_register";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url,"root","root");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT image FROM user ");
int i = 1;
if(rs.next()) {
Blob len1 = rs.getBlob("image");
int len = (int)len1.length();
byte[] b = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index = readImg.read(b, 0, len);
System.out.println("index" +index);
stmt.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(b,0,len);
response.getOutputStream().flush();
}
} catch(Exception ex) {
out.println(ex);
} finally {
rs.close();
stmt.close();
con.close();
}
%>
<br>
<center><input type="button" value="Print" onclick="window.print();return false;" /> </center>
</body>
</html>
Can anyone suggest how can i display multiple images on jsp page?
Instead of if(rs.next()) {} you have to use while(rs.next()){}

Categories