servlet page shows blank when accessed later - java

I have a strange issue with servlet page. I have simple web application which contains just a servlet.I deployed it in Tomcat 7. When user enters url, the servlet should get directly executed, get the data from the database and print the output. But it shows blank page after some time. When I undeploy and deploy, it shows data. After some time when I access the page, it shows blank page. Then again when I redeploy, it shows data. Can someone please let me know how to resolve this? I have no clue why it happens. Below is my code.
I am using mysql database.mysql-connector-java-5.1.29-bin.jar added in lib folder and added to buildpath.
public class Homeservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static final String mysqldblink = "************";
static final String mysqlUsername = "username";
static final String mysqlPassword = "pw";
Connection connection =null;
Statement stmt = null;
/**
* #see HttpServlet#HttpServlet()
*/
public Homeservlet() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(mysqldblink,
mysqlUsername, mysqlPassword);
stmt = connection.createStatement();
}
catch(Exception E)
{
E.printStackTrace();
}
}
#Override
public void service(ServletRequest request, ServletResponse response)
{
PrintWriter pw = null;
try {
String query = "querytogetdata";
pw = response.getWriter();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
pw.println(rs.getString(1));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}finally{
try{
pw.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void destroy( ) {
// Close the connection
try {
if (connection != null)
connection.close( );
if(stmt != null)
stmt.close();
} catch (SQLException ignore) { }
}
}

Related

JBoss EAP 7 with Oracle Datasource

I am trying to access an Oracle DB connection using Jboss datasource but it's throwing java.lang.NullPointerException.
Below is my code and jboss shows below logs during startup.
What's wrong in my code?
WFLYJCA0001: Bound data source [java:/jdbc/testOracleDS]
#WebServlet("/Index")
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
private DataSource dataSource;
Connection conn = null;
public Index() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
try {
DataSource anotherDataSource = InitialContext.doLookup("java:/jdbc/testOracleDS");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
conn = dataSource.getConnection();
System.out.println("connection established");
response.getWriter().println("connection established");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("failed to establish connection: " + e);
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
I fixed this issue by adjusting code, The Datasource variable was not correctly initialized
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
private DataSource dataSource;
Connection conn = null;
public Index() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
try {
dataSource = InitialContext.doLookup("java:/jdbc/testOracleDS");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
conn = dataSource.getConnection();
System.out.println("connection established");
response.getWriter().println("connection established");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("failed to establish connection: " + e);
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}}

Java Error can't find the symbol

Hi I am trying to get a login information through the JSP's. I got an error Can't find symbol : Login while compiling LoginServlet.java
Here is my code, can you please tell the solution of that problem?
Login.java
public class Login
{
public static boolean validate(String name, String pass)
{
boolean status = false;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:oracle:thin:#localhost:1521:xe";
String driver = "oracle.jdbc.driver.OracleDriver";
String userName = "system";
String password = "dad";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,userName, password);
pst = conn.prepareStatement("select * from login where user=? and password=?");
pst.setString(1, name);
pst.setString(2, pass);
rs = pst.executeQuery();
status = rs.next();
}
catch (Exception e)
{
System.out.println(e);
}
finally
{
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return status;
}
}
LoginServlet.java
public class LoginServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void do Post(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("name", n);
session.setAttribute("pass", p);
if(Login.validate(n,p))
{
Request Dispatcher rd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
}
else
{
out.print("<p style=\"color:red\">Sorry username or password error</p>");
Request Dispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
out.close();
}
}
You need to import you Login class in your Servlet.
It might be due to your Login class and LoginServlet both are in different packages. So you need to import Login class in your LoginServlet, before using it.
You need to add something like,
import yourpackage.Login; in the beginning of the LoginServlet
import the Login class in to the LoginServlet.java .
If both are in same package then you have to add it into class path.
it may be helpful for you.
thanks

Datasource error when migrating from Tomcat server to JBoss?

I would appreciate if anyone can help me out here. I have developed an application using Apache Tomcat and it is deployed and working. However when I wanted to migrate the app to JBoss and deploy the WAR file on that server, I got a datasource error. I'm new to JBoss and I have no clue on what should I do next to solve this issue. I would appreciate if someone could guide me through this process!
My DBConnector class code:
import java.sql.*;
import java.util.Properties;
import java.io.InputStream;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory;
public class DbConnector {
private static String JDBC_DRIVER = "jdbc.driver";
private static String JDBC_URL = "jdbc.url";
private static String JDBC_USER = "jdbc.user";
private static String JDBC_PASSWORD = "jdbc.password";
private static Properties props = new Properties();
private Connection connection = null;
private Statement stat = null;
private ResultSet rs = null;
private static volatile DataSource dsObj;
static {
try {
// a way to retrieve the data in
// connection.properties found
// in WEB-INF/classes
InputStream is = DbConnector.class.getResourceAsStream("/connection.properties");
props.load(is);
//PropertyConfigurator.configure("log4j.properties");
} catch (Exception e) {
e.printStackTrace();
}
try {
Class.forName(props.getProperty(JDBC_DRIVER)).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void initialize() {
try {
dsObj = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Constructor
*/
public DbConnector() {
try {
initialize();
this.connection = getConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns DB Connection
* #return Connection
* #throws SQLException
*/
public static Connection getConnectionFromPool() throws SQLException {
Connection connection = null;
// checking for null singleton instance
if (null == dsObj) { // synchronized over class to make thread safe
synchronized (DbConnector.class) {
// double checking for making singleton instance thread safe
if (null == dsObj) {
initialize();
}
}
}
// getting connection from data sourceconnection = dsObj.getConnection();
return connection;
}
/**
* Get Connection
* #return Connection object
* #throws SQLException
*/
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(props.getProperty(JDBC_URL), props.getProperty(JDBC_USER), props.getProperty(JDBC_PASSWORD));
}
/**
* Execute Query
* Purpose: SELECT
* #param sql SQL Statement
* #return ResultSet
*/
public ResultSet executeQuery(String sql) {
try {
if (connection == null) {
return null;
}
stat = connection.createStatement();
rs = stat.executeQuery(sql);
return rs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Execute Update
* Purpose: Insert, Update, Delete
* #param sql SQL Statement
* #return int No. of Rows Updated
*/
public int executeUpdate(String sql) {
try {
if (connection == null) {
return -1;
}
stat = connection.createStatement();
return stat.executeUpdate(sql);
} catch (Exception e) {
//e.printStackTrace();
return -1;
}
}
/**
* Execute
* Purpose: Create, Drop
* #param sql statement to update.
* #return true is statement execute sucessfuly and false otherwise
*/
public boolean execute(String sql) {
try {
if (connection == null) {
return false;
}
stat = connection.createStatement();
return stat.execute(sql);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
/**
* Close ResultSet
*/
public void closeResultSet() {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
}
/**
* Close Statement
*/
public void closeStatement() {
if (stat != null) {
try {
stat.close();
} catch (Exception e) {
e.printStackTrace();
//log.error(e);
}
}
}
/**
* Close Connection
*/
public void closeConnection() {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Close
* Connection, Statement and Resultset *
*/
public void close() {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stat != null) {
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
After reading about this online, I know I have to do something to the context.xml and web.xml files.
Would someone show me some sample code or give me some assistance with this please?
The first thing I do is get rid of your own connection pool code and use the one provided by the container. You basically define the DataSource and the container (Tomcat/JBOSS) will make it available to your application via JNDI. Once defined, you can refer to it in your web.xml. Search google for how-to.
<resource-ref>
<description>Customer Database</description>
<res-ref-name>jdbc/CustomerDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
UPDATE
If you still want to make this work your way, then make sure you have the jar file containing the org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory in your classpath (WEB-INF/lib). And post the stacktrace you are getting.
UPDATE 2
The error is very clear
Web mapping already exists for deployment URL file:/C:/Users/Dane/Desktop/jboss-as-distribution-6.0.0.Final/jboss-6.0.0.Final/server/default/tmp/vfs/automountec9d6360903186ac/SurveyApplication.war-a018e9cb945f462b/
Seems like you already have another application deployed with the same context path.

MySQL JDBC returning 0 results

It seems a very basic question but I couldn't find any resolution for it.
I have following code with me:
package com.test.db.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCConnect
{
private Connection conn = null;
private final String uname = "root";
private final String passwd = "test#123";
private String url = "jdbc:mysql://127.0.0.1:3306/TrainDB";
private final String className = "com.mysql.jdbc.Driver";
public void initConnection()
{
try
{
if(this.conn == null || this.conn.isClosed())
{
try
{
Class.forName (className).newInstance ();
this.conn = DriverManager.getConnection(url, uname, passwd);
System.out.println("database connection established.");
}
catch(SQLException sqe)
{
sqe.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
//return this.conn;
}
public void disconnect()
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
public void insertData(String sql)
{
PreparedStatement s;
try
{
if(conn == null || conn.isClosed())
{
initConnection();
}
s = conn.prepareStatement(sql);
int count = s.executeUpdate ();
s.close ();
System.out.println (count + " rows were inserted");
}
catch (SQLException e)
{
e.printStackTrace();
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception se) { /* ignore close errors */ }
}
}
}
public ResultSet query(String sql)
{
Statement s = null;
try
{
if(this.conn == null || this.conn.isClosed())
{
initConnection();
}
s = conn.createStatement();
s.executeQuery(sql);
ResultSet rs = s.getResultSet();
System.out.println("lets see " + rs.getFetchSize());
return rs;
}
catch(SQLException sq)
{
System.out.println("Error in query");
return null;
}
finally
{
try {
s.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I am using JDBCConnect in a different class:
import java.sql.ResultSet;
import java.sql.SQLException;
public class traininfo
{
public static void main(String[] args)
{
JDBCConnect jdbcConn = new JDBCConnect();
String sql = "SELECT id FROM testtable";
ResultSet rs = jdbcConn.query(sql);
try {
System.out.println(rs.getFetchSize());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(rs != null)
{
try
{
while(rs.next())
{
System.out.println(rs.getString("id"));
}
rs.close();
}
catch(SQLException sqe)
{
}
}
jdbcConn.disconnect();
}
}
I am not using concurrent calls for insertion and reads. If I use the same query in mysql-workbench (client), I am getting proper results but using the mentioned code, I am getting
database connection established.
lets see 0
0
Database connection terminated
Please suggest me what I am missing?
Most probably it's because you're closing Statement before you are using it's ResultSet. It's strange that it doesn't throw an exception, but this is not correct anyway.
As per Statement.close method JavaDoc:
When a Statement object is closed, its current ResultSet object, if one exists, is also closed.
I suggest to use some kind of callback to retrieve results from ResultSet before it's closed e.g.:
public <T> T query(String sql, IResultSetHandler<T> resultSetHandler ) throws SQLException {
Statement statement = null;
try {
statement = connection.createStatement();
final ResultSet rs = connection.executeQuery(sql);
final T result = resultSetHandler.handle(rs);
return result;
} finally {
if(statement != null) {
statement.close();
}
}
}
public interface IResultSetHandler<T> {
T handle(ResultSet rs);
}
public static void main(String[] args) {
JDBCConnect jdbcConn = new JDBCConnect();
List<String> ids = jdbcConn.query(sql, new IResultSetHandler<List<String>>() {
public List<String> handle(ResultSet rs) {
List<String> ids = new ArrayList<String>();
while(rs.next()) {
ids.add(rs.getString("id"));
}
return ids;
}
});
}
Or to use commons apache dbutils library which does exactly the same.
ResultSet.getFetchSize() lets you know the maximum number of rows that the connection will fetch at once. You can set it with ResultSet.setFetchSize(int). See also the official documentation. It does not tell you how many rows in total you will get. If the fetch size is left to zero, JDBC decides on its own.
Other than that, refer to Yura's answer which addresses the core of your problem.
Could it be because you never call InsertRows, as it never shows that 'X rows were inserted'

can't get connection to database through java class

i'm trying to establish connection with mysql database through file properties and then run the information from servlet. my Connection class looks like this:
public class pageDao {
private Connection connection;
private Statement statement;
private pageDao() {
Properties prop = new Properties();
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " +cnfe);
}
try {
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String db = prop.getProperty("database");
String dbuser = prop.getProperty("dbuser");
String dbpassword = prop.getProperty("dbpassword");
connection = DriverManager.getConnection(db,dbuser,dbpassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static pageDao thisDao;
public static pageDao gedDao()
{
if(thisDao == null)
thisDao = new pageDao();
return thisDao;
}
public PageData getPage(String id)
{
PageData data = new PageData();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from pages where id='"+id+"'");
if(rs.next())
{
data.setId(rs.getString("id"));
data.setParentid(rs.getString("parentid"));
data.setTitle(rs.getString("title"));
data.setTitle4menu(rs.getString("title4menu"));
data.setKeywords(rs.getString("keywords"));
data.setDescription(rs.getString("description"));
data.setMaintext(rs.getString("maintext"));
}
else
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
when i run it, it doesn't show the mistake that connection wasn't established, but when it gets to the
public PageData getPage(String id) {
PageData data = new PageData();
try {
statement = connection.createStatement();
it throws java.lang.NullPointerException.
can anybody help me out with that?
there is no issue with code.
check your passing parameter ...
check sample
private Connection getConnection() {
try {
String dbUrl = "jdbc:mysql://localhost:3306/projectmining";
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(dbUrl, "root", "admin");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

Categories