-1

I'm still newbie on JSP or Java. I am currently using the existing Java code so called Conn.java as following:

  package org.myclass.auth;

  import java.sql.*;
  import org.myclass.global.Variable;
  import org.myclass.auth.LoadProps;
  import org.apache.commons.dbcp.BasicDataSource;
  import javax.sql.DataSource;

  public class Conn {
     String success = "";
  public LoadProps app;
  public Variable var = new Variable();
  Connection conn = null;
  Statement st = null;
  ResultSet rs = null;
  int x = 0;

  public Conn(String path)  {
     app = new LoadProps(path);
  }
  public Conn()  {
     app = new LoadProps(var.getPATH());
  }
  public boolean open() {
     boolean success = false;

    try {
        DataSource dataSource = setupDataSource(app.getUrl(), app.getUser(), app.getPassword());
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return success;
  }
  public DataSource setupDataSource(String connectURI, String connectUser, String connectPassword) {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUsername(connectUser);
    ds.setPassword(connectPassword);
    ds.setUrl(connectURI);
return ds;
   }
  public static void printDataSourceStats(DataSource ds) throws SQLException {
     BasicDataSource bds = (BasicDataSource) ds;
  }

  public static void shutdownDataSource(DataSource ds) throws SQLException {
     BasicDataSource bds = (BasicDataSource) ds;
     bds.close();
  }

  public String getUrl()  {
     return app.getUrl();
  }
  public String getUser()  {
     return app.getUser();
  }
  public String getPassword()  {
    return app.getPassword();   
  }

  public void close() throws SQLException {
      if(!conn.isClosed())    {
        conn.close();
     }
  }
  public ResultSet query(String query)    {
      try {         
         st = conn.createStatement();  
         rs = st.executeQuery(query);
     }
     catch(SQLException sqle) {
        sqle.printStackTrace();
     }
    return rs;
   }
   public boolean queryInsert(String query)    {
       boolean value = false;
      try {
        st = conn.createStatement();
        value = st.execute(query);            
        value = true;
    }
    catch(SQLException sqle) {
        sqle.printStackTrace();
    }
    return value;
    }
   public int queryUpdate(String query)    {
       int value = 0;
       try {
            st = conn.createStatement();
           value = st.executeUpdate(query);
       }
       catch(SQLException sqle) {
          sqle.printStackTrace();
     }
    return value;
}

}

in order to use PreparedStatement, so later on I only call this on my JSP codes such as:

    <%@ page import="java.io.*,java.util.*,java.sql.*"%>
    <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
    <%@ page import="org.myclass.auth.Conn" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>


    <%    
        String query = "SELECT adminid FROM administrator where username =  '"+ session.getAttribute("username") +"'";
        Conn conn = new Conn();
        ResultSet rsQ;
        conn.open();
        rsQ = conn.query(query);
        rsQ.next();

        int adminid = rsQ.getInt(1);
        conn.close();


        Conn conn1 = new Conn();
        String insert = "INSERT INTO campaign  (uid,sender_id,content,Starttime,status,lastmodifiedid,creationtime,msisdnfile) VALUES('"+ adminid +"','"+ request.getParameter("sender_id") +"','"+request.getParameter("message")+"','"+request.getParameter("startTime")+"','Running','"+adminid+"',now(),'file2.txt')";
        out.print(insert);
        conn1.open();
        conn1.queryInsert(insert);
        conn1.close();
    %>

What am i supposed to do to modify the Conn.java since when I ran the JSP it returns NULL when it goes to conn1.queryInsert(insert)? And one more thing, what if I use PreparedStatement, what should I do then to keep my JSP the same as above? Thanks in advance

Doni Andri Cahyono
  • 793
  • 5
  • 16
  • 28

3 Answers3

0

Please Note: This is not advised to keep any business or data access logic in JSPs. JSPs are meant for presentation purpose ONLY. Such data access related code should be moved in server side JAVA classes. Please read about MVC(Model-View-Controller) pattern to learn more.

Get a statement object using your connection, pass your string query and run executeUpdate as below:

   conn1.open();
   Statement statement = conn1.createStatement();
   statement.executeUpdate(insert);
   conn1.close();
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • 1
    In these cases, the best answer would be to apply a good MVC pattern by stop using scriptlets: [How to avoid Java Code in JSP-Files?](http://stackoverflow.com/q/3177733/1065197). Once this achieved, the problem would be a piece of cake and the JSPs would at least display in browsers. – Luiggi Mendoza Oct 24 '12 at 03:25
  • @LuiggiMendoza: +1. That's what I was thinking too. – Bhesh Gurung Oct 24 '12 at 03:26
  • @BheshGurung to access the link easily, visit the [JSP wiki](http://stackoverflow.com/tags/jsp/info) and go to the FAQ section. – Luiggi Mendoza Oct 24 '12 at 03:27
  • @LuiggiMendoza: :) I thought it was more about learning. I do agree, business/data logic shouldn't be written in JSP. I will add a statement in the answer. – Yogendra Singh Oct 24 '12 at 03:28
  • @YogendraSingh nice to know you know that, then spread the best practices! Don't give a fish to a fisherman, teach him how to go fishing by himself. – Luiggi Mendoza Oct 24 '12 at 03:29
  • @LuiggiMendoza Being new here, learning, what to answer, what not to answer. Most of the times, I see people answering silly commas and arraylist and here we are talking about standards. Will learn :) – Yogendra Singh Oct 24 '12 at 03:33
0

Don't do that, please. Keep it to your Data Access Layer. Don't mess up your JSP with SQL related code.

Furthermore, don't pollute your JSP with Java code. Therefore, replace the scriplets with JSTL/EL instead.

Community
  • 1
  • 1
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
0

According to the MVC2 rules, all the logics related to database issues should be kept in persistence layer using DB bean or Hibernate, JDO like frameworks. And all the business logics should be kept in either bean classes or spring bean, ejb session bean component. If you are using only jsp in any small application, just follow these steps:

  1. Create a separate simple or Bean class taking all the properties as private
  2. Write your logic in that class in the form of public methods
  3. Use <jsp:useBean>, <jsp:setProperty> and <jsp:getProperty> like tags in your jsp pages to access the object of your bean class
  4. call the required methods of your Bean class using id(object refrence)

And placing java code in jsp is not recommended, so try to use jstl or custom tags .

I hope it'll help you... :)

Shailesh Saxena
  • 3,472
  • 2
  • 18
  • 28