0

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) { }
      }     

}
Apparatus
  • 411
  • 1
  • 5
  • 19
  • why resultset is not closed? you are using same connection and statement. – Braj Jun 15 '14 at 17:14
  • @Braj I believe when rs is iterated, then resultset gets automatically closed. I closed statement in destroy() method. Am I doing something wrong? – Apparatus Jun 15 '14 at 17:16
  • So instead of overriding `doGet()` or `doPost()` you prefer to override `service()` method, why? `service()` method internally calls `doGet()` or `doPost()` based on request method type. – Braj Jun 15 '14 at 17:17
  • I think that you should look up your logs. There you can find something interest. Besides, don't forget that servlet is always in one instance and if it sometime works sometimes not maybe some problems occur in its fields. –  Jun 15 '14 at 17:18
  • @Braj Because I want the page to be shown as soon as someone accesses the url. If I use doGet() or doPost(), it's not showing anything automatically. – Apparatus Jun 15 '14 at 17:19
  • Your assumption is completely wrong. even if you use `doGet()` or `doPost()` it shows the page whenever it is accessed. – Braj Jun 15 '14 at 17:20
  • @Braj Might be as I am beginner in java web-app. As far as I understood, I followed this. Can you please let me know how it has to be done? – Apparatus Jun 15 '14 at 17:21
  • 1
    If you are hitting this servlet directly by entering the URL in browser window then its a GET request or if you are calling it from any form submission having method attribute as post then it's a POST request and based on request servlet methods are called. It might help you, [Java Servlet Technology](http://www.oracle.com/technetwork/java/index-jsp-135475.html) – Braj Jun 15 '14 at 17:23
  • you are using single connection that will impact the other users that access the same page simultaneously. Instead create a connection whenever required and just close it when finished. use connection pool for good performance. It might help you [My ConnctionUtil Class](http://stackoverflow.com/questions/22999830/servlet-server-side-initialization-code-in-gwt/23006184#23006184) – Braj Jun 15 '14 at 17:27
  • Actually I've never seen such driver before, what version of db are you using? – Roman C Jun 15 '14 at 17:30
  • @Braj Yes, I want to hit the servlet directly by entering the URL. Remaining part I know.I think there is some db connectivity issue after some time when the deployment happens. Am I coding it in correct way about the db connection? – Apparatus Jun 15 '14 at 17:38
  • @RomanC I edited the driver name. – Apparatus Jun 15 '14 at 17:39
  • @Braj I am sorry, I have seen your answer which you linked. I am unable to understand how to replace my code(which has mysql and using tomcat) with that code and how to use that connectionutil in my servlet – Apparatus Jun 15 '14 at 17:46
  • That will not resolve your issue, its just for further improvement in your code. Can you try it again after moving the code in overridden `doGet()` from `service()` method and just remove `service()` method. create the connection and statement in `doGet()` rather that in `init()` method. – Braj Jun 15 '14 at 17:48
  • 1
    @Braj Thanks, I moved the service() code to doGet(). It works at the moment, but I don't know whether it works later. How can I improve the db connection thing now? – Apparatus Jun 15 '14 at 17:53
  • 1
    Sounds good, I have already share you a link. use connection pool and prepared statement instead of statement. – Braj Jun 15 '14 at 17:56
  • @Braj Yes, thanks. But I am not getting how to use them in my servlet code and where to place that datasource tags content. Anyways thanks. – Apparatus Jun 15 '14 at 18:02
  • 1
    No worries take your time, just read it more on Google. Don't do simply copy-paste, try to learn it first. – Braj Jun 15 '14 at 18:03

0 Answers0