Results 1 to 2 of 2
  1. #1
    smartboy3k is offline Member
    Join Date
    Dec 2008
    Posts
    1
    Rep Power
    0

    Default [SOLVED] Unable to connect to Derby from jsp pages

    Hello All,

    Im novice in java. i was asked to develop a small web application using derby as database. I created a class as below which connects to derby as follows:

    public static Connection getConnection(String dataBaseName) {
    String url = "jdbc:derby://localhost:1527/";
    String driver = "org.apache.derby.jdbc.ClientDriver";
    try {
    Class.forName(driver);
    con = DriverManager.getConnection(url + dataBaseName,"chakri","chakri");
    System.out.println("Connection is created...");
    // con.close();
    } catch (Exception e) {
    System.out.println(e);
    }
    return con;
    }


    later, in jsp page im trying to establish connection as shown below:

    <%
    DerbyConnection dn = new DerbyConnection();
    dn.getConnection("mydatabase");
    %>

    i also added the derbyClient.jar to the build path in Eclipse. But when i run my jsp it is throwing ClassNotFound exception. Please help me out on this.

    ================================================== ======================


    DerbyConnection.Java
    ----------------------
    package session15;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;

    import org.apache.catalina.Realm;

    public class DerbyConnection {
    static Connection con = null;

    public static Connection getConnection(String dataBaseName) {
    String url = "jdbc:derby://localhost:1527/";
    String driver = "org.apache.derby.jdbc.ClientDriver";
    try {
    Class.forName(driver);
    con = DriverManager.getConnection(url + dataBaseName,"chakri","chakri");
    System.out.println("Connection is created...");
    // con.close();
    } catch (Exception e) {
    System.out.println(e);
    }
    return con;
    }

    public static void closeConnection() {
    try {
    con.close();
    System.out.println("Connection is closed...");
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    /*org.apache.catalina.Realm rm;
    rm.findSecurityConstraints(arg0, arg1);
    rm.authenticate(arg0);
    rm.getContainer();
    rm.getInfo();
    rm.hasResourcePermission(arg0, arg1, arg2, arg3);
    rm.hasRole(arg0, arg1);
    rm.setContainer(arg0);*/
    }

    }



    Question.java
    ---------------
    package session14;

    import java.io.Serializable;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;

    public class Question implements Serializable, QuestionInterface {


    static int index=0;
    private String description;
    private String[] options = new String[4];
    private boolean isMultiAnswerQuestion;
    private String[] correctOptions = new String[4];

    public void setDescription(String description) {
    this.description = description;
    }

    public void setOptions(String[] options) {
    this.options = options;
    }

    public void setMultiAnswerQuestion(boolean isMultiAnswerQuestion) {
    this.isMultiAnswerQuestion = isMultiAnswerQuestion;
    }

    public void setCorrectOptions(String[] correctOptions) {
    this.correctOptions = correctOptions;
    }

    @Override
    public String[] getCorrectOptions() {
    return correctOptions;
    }

    @Override
    public String getDescription() {
    return description;
    }

    @Override
    public String[] getOptions() {
    return options;
    }

    @Override
    public boolean isMultiAnswerQuestion() {
    return isMultiAnswerQuestion;
    }

    public void insertQuestion(Connection con) throws SQLException {
    index++;
    String multi="";
    PreparedStatement statement;
    statement = con.prepareStatement("insert into Questions values(?,?,?)");
    if (this.isMultiAnswerQuestion){
    multi="Y";
    }else{
    multi="N";
    }

    statement.setInt(1, index);
    statement.setString(2, this.getDescription());
    statement.setString(3, multi);
    statement.execute();
    statement.close();

    for (String opt : this.getOptions())
    {
    statement = con.prepareStatement("insert into Options values(?,?)");
    statement.setInt(1, index);
    statement.setString(2, opt);
    statement.execute();
    statement.close();
    }

    for (String ans : this.getCorrectOptions())
    {
    statement = con.prepareStatement("insert into Answers values(?,?)");
    statement.setInt(1, index);
    statement.setString(2, ans);
    statement.execute();
    statement.close();
    }
    }


    }




    QuestionBank.java
    ------------------
    package session14;

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.PreparedStatement;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Random;
    import java.util.Vector;

    public class QuestionBank implements Serializable, QuestionBankInterface {

    private Collection<Question> poolOfQuestions;

    @Override
    public boolean addQuestion(Question question) {

    return this.poolOfQuestions.add(question);
    }

    @Override
    public int getQuestionCount() {
    return poolOfQuestions.size();
    }

    @Override
    public Collection<Question> getRandomQuestionSet(int count) {
    Random randomNumber = new Random();
    int i = 0;
    boolean flag = true;
    ArrayList<Question> allQuestionsVector = (ArrayList<Question>) poolOfQuestions;
    ArrayList<Question> v = new ArrayList<Question>();

    Collection<Question> qSet = new HashSet<Question>();

    while (flag) {
    int nextNum = randomNumber.nextInt(10);
    Question q = allQuestionsVector.get(nextNum);
    if (qSet.add(q)) {
    v.add(q);
    i++;
    }
    if (i > 5)
    flag = false;
    }
    qSet = null;
    return v;
    }

    @Override
    public boolean removeQuestion(Question question) {

    return poolOfQuestions.remove(question);
    }

    public void generateQuestion() {
    poolOfQuestions = new ArrayList<Question>();

    Question q1 = new Question();
    q1.setDescription("1+1=?");
    String[] options1 = new String[4];
    options1[0] = "Sum is 1";
    options1[1] = "Sum is 2";
    options1[2] = "Sum is 3";
    options1[3] = "Sum is 4";
    q1.setOptions(options1);
    q1.setMultiAnswerQuestion(false);
    String[] answer1 = new String[4];
    answer1[0] = "1";
    answer1[1] = "-1";
    answer1[2] = "-1";
    answer1[3] = "-1";
    q1.setCorrectOptions(answer1);
    addQuestion(q1);

    Question q2 = new Question();
    q2.setDescription("8 is divisible by?");
    String[] options2 = new String[4];
    options2[0] = "4";
    options2[1] = "2";
    options2[2] = "3";
    options2[3] = "All";
    q2.setOptions(options2);
    q2.setMultiAnswerQuestion(true);
    String[] answer2 = new String[4];
    answer2[0] = "0";
    answer2[1] = "1";
    answer2[2] = "-1";
    answer2[3] = "-1";
    q2.setCorrectOptions(answer2);
    addQuestion(q2);

    Question q3 = new Question();
    q3.setDescription("What is right angled traiangle?");
    String[] options3 = new String[4];
    options3[0] = "Sum of all angels whould be 90";
    options3[1] = "All the angles should be less than 90";
    options3[2] = "Atleast One Angle in the triangle should be 90";
    options3[3] = "None";
    q3.setOptions(options3);
    q3.setMultiAnswerQuestion(false);
    String[] answer3 = new String[4];
    answer3[0] = "2";
    answer3[1] = "-1";
    answer3[2] = "-1";
    answer3[3] = "-1";
    q3.setCorrectOptions(answer3);
    addQuestion(q3);

    Question q4 = new Question();
    q4.setDescription("Formula for calculating Area of Rhombus?");
    String[] options4 = new String[4];
    options4[0] = "Area = (B + H)/2";
    options4[1] = "Area = (B + H)*2";
    options4[2] = "Area = (B x H)/2";
    options4[3] = "Area = B x H";
    q4.setOptions(options4);
    q4.setMultiAnswerQuestion(false);
    String[] answer4 = new String[4];
    answer4[0] = "3";
    answer4[1] = "-1";
    answer4[2] = "-1";
    answer4[3] = "-1";
    q4.setCorrectOptions(answer4);
    addQuestion(q4);

    Question q5 = new Question();
    q5.setDescription("How many sides does Hexagon have?");
    String[] options5 = new String[4];
    options5[0] = "3";
    options5[1] = "4";
    options5[2] = "5";
    options5[3] = "6";
    q5.setOptions(options5);
    q5.setMultiAnswerQuestion(false);
    String[] answer5 = new String[4];
    answer5[0] = "3";
    answer5[1] = "-1";
    answer5[2] = "-1";
    answer5[3] = "-1";
    q5.setCorrectOptions(answer5);
    addQuestion(q5);

    Question q6 = new Question();
    q6.setDescription("How many sides does Triangle have?");
    String[] options6 = new String[4];
    options6[0] = "3";
    options6[1] = "4";
    options6[2] = "5";
    options6[3] = "6";
    q6.setOptions(options6);
    q6.setMultiAnswerQuestion(false);
    String[] answer6 = new String[4];
    answer6[0] = "0";
    answer6[1] = "-1";
    answer6[2] = "-1";
    answer6[3] = "-1";
    q6.setCorrectOptions(answer6);
    addQuestion(q6);

    Question q7 = new Question();
    q7.setDescription("what is the radius of Circle?");
    String[] options7 = new String[4];
    options7[0] = "360";
    options7[1] = "40";
    options7[2] = "95";
    options7[3] = "67";
    q7.setOptions(options7);
    q7.setMultiAnswerQuestion(false);
    String[] answer7 = new String[4];
    answer7[0] = "0";
    answer7[1] = "-1";
    answer7[2] = "-1";
    answer7[3] = "-1";
    q7.setCorrectOptions(answer7);
    addQuestion(q7);

    Question q8 = new Question();
    q8.setDescription("Dogs Love?");
    String[] options8 = new String[4];
    options8[0] = "Milk";
    options8[1] = "Coke";
    options8[2] = "Chips";
    options8[3] = "Pastry";
    q8.setOptions(options8);
    q8.setMultiAnswerQuestion(false);
    String[] answer8 = new String[4];
    answer8[0] = "0";
    answer8[1] = "-1";
    answer8[2] = "-1";
    answer8[3] = "-1";
    q8.setCorrectOptions(answer8);
    addQuestion(q8);

    Question q9 = new Question();
    q9.setDescription("Which is not part of Computer?");
    String[] options9 = new String[4];
    options9[0] = "Steering";
    options9[1] = "Mouse";
    options9[2] = "Keyboard";
    options9[3] = "RAM";
    q9.setOptions(options9);
    q9.setMultiAnswerQuestion(false);
    String[] answer9 = new String[4];
    answer9[0] = "0";
    answer9[1] = "-1";
    answer9[2] = "-1";
    answer9[3] = "-1";
    q9.setCorrectOptions(answer9);
    addQuestion(q9);

    Question q10 = new Question();
    q10.setDescription("Capital Of AP?");
    String[] options10 = new String[4];
    options10[0] = "Nellore";
    options10[1] = "Tirupati";
    options10[2] = "Secunderabad";
    options10[3] = "None of these";
    q10.setOptions(options10);
    q10.setMultiAnswerQuestion(false);
    String[] answer10 = new String[4];
    answer10[0] = "3";
    answer10[1] = "-1";
    answer10[2] = "-1";
    answer10[3] = "-1";
    q10.setCorrectOptions(answer10);
    addQuestion(q10);

    Question q11 = new Question();
    q11.setDescription("Chicago is in which country?");
    String[] options11 = new String[4];
    options11[0] = "India";
    options11[1] = "Australia";
    options11[2] = "China";
    options11[3] = "None of these";
    q11.setOptions(options11);
    q11.setMultiAnswerQuestion(false);
    String[] answer11 = new String[4];
    answer11[0] = "3";
    answer11[1] = "-1";
    answer11[2] = "-1";
    answer11[3] = "-1";
    q11.setCorrectOptions(answer11);
    addQuestion(q11);

    Question q12 = new Question();
    q12.setDescription("H20 represents?");
    String[] options12 = new String[4];
    options12[0] = "Water";
    options12[1] = "Oxygen";
    options12[2] = "Magnesium";
    options12[3] = "Hydrogen";
    q12.setOptions(options12);
    q12.setMultiAnswerQuestion(false);
    String[] answer12 = new String[4];
    answer12[0] = "3";
    answer12[1] = "-1";
    answer12[2] = "-1";
    answer12[3] = "-1";
    q12.setCorrectOptions(answer12);
    addQuestion(q12);
    }

    public boolean saveToDB(Connection con) throws SQLException {
    int index = 0;
    boolean flag=true;
    try {
    generateQuestion();
    ArrayList<Question> allQuestions = (ArrayList<Question>) poolOfQuestions;
    for (Question ques : allQuestions) {
    ques.insertQuestion(con);
    }
    } catch (Exception ex) {
    flag=false;
    System.err.println("Exception: " + ex.getMessage());
    } finally {
    con.close();
    }
    return flag;

    }

    public boolean loadFromDB(Connection con) {
    int index = 1;
    boolean flag=true;
    PreparedStatement statement;
    try {
    statement = con.prepareStatement("select * from Questions");
    ResultSet rSet = statement.executeQuery();
    while (rSet.next()) {
    Question question = new Question();
    index = Integer.parseInt(rSet.getString("qid"));
    // ----------------- DISPLAY -----------------------------
    System.out.println("Question"+index+": "+rSet.getString("descriptions"));
    question.setDescription((rSet.getString("descripti ons")));
    if ("Y".equals(rSet.getString("qid"))) {
    System.out.println("IS MULTI ANSWER: TRUE");
    question.setMultiAnswerQuestion(true);
    } else {
    System.out.println("IS MULTI ANSWER: FALSE");
    question.setMultiAnswerQuestion(false);
    }
    //statement.close();
    //rSet.close();
    //System.out.println("select * from Options where Qid="+index);
    PreparedStatement optionsStatement = con.prepareStatement("select * from Options where Qid=?");
    optionsStatement.setInt(1, index);
    ResultSet optRSet = optionsStatement.executeQuery();

    String[] options = new String[4];
    int optIndex=0;
    System.out.print("Options: ");
    while (optRSet.next())
    {
    System.out.print(optRSet.getString("Q_OPTIONS")+"\ t");
    options[optIndex]=optRSet.getString("Q_OPTIONS");
    optIndex++;
    }
    question.setOptions(options);

    // Adding Right Answer
    PreparedStatement ansStatement = con.prepareStatement("select * from Answers where Qid=?");
    ansStatement.setInt(1, index);
    ResultSet ansRSet = ansStatement.executeQuery();

    String[] answers = new String[4];
    int ansIndex=0;
    System.out.print("Answer: ");
    while (ansRSet.next())
    {
    System.out.print(ansRSet.getString("Q_ANSWERS")+"\ t");
    answers[ansIndex]=ansRSet.getString("Q_ANSWERS");
    ansIndex++;
    }
    question.setCorrectOptions(answers);

    index++;
    }

    statement.close();
    con.close();
    } catch (SQLException ex) {
    flag=false;
    System.err.println("SQLException: " + ex.getMessage());
    }
    return flag;

    }

    }



    QuestionBankInterface.java
    --------------------------
    package session14;

    import java.util.Collection;

    public interface QuestionBankInterface {

    public int getQuestionCount();

    public Collection<Question> getRandomQuestionSet(int count);

    public boolean addQuestion(Question question);

    public boolean removeQuestion(Question question);
    }



    QuestionInterface.java
    ----------------------
    package session14;

    public interface QuestionInterface {

    public String getDescription();

    public String[] getOptions();

    public boolean isMultiAnswerQuestion();

    public String[] getCorrectOptions();
    }



    ExamAttempt.java
    --------------------
    package session14;

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Collection;
    import java.util.HashSet;
    import java.util.Properties;

    public class ExamAttempt implements Serializable, ExamAttemptInterface {

    private String studentName;
    private String examType;
    private Collection<Question> questionSet;
    private int score;
    private int minPassScore;
    private int maxScore;
    private Calendar examStartTime;
    private Calendar examEndTime;
    private String[] userInputAnswers = new String[4];

    @Override
    public String[] getAnsForQuestion(Question question) {
    return question.getCorrectOptions();

    }

    @Override
    public String getExamType() {
    return examType;
    }

    @Override
    public int getMaxScore() {
    return maxScore;
    }

    @Override
    public int getMinPassScore() {

    return minPassScore;
    }

    @Override
    public Collection<Question> getQuestionSet() {
    return questionSet;
    }

    @Override
    public int getScore() {
    return score;
    }

    @Override
    public String getStudentName() {

    return studentName;
    }

    public void setStudentName(String studentName) {
    this.studentName = studentName;
    }

    @Override
    public int getTimeTaken() {

    return 30; // (examEndTime-examStartTime;
    }

    public void setQuestionSet(Collection<Question> questionSet) {
    this.questionSet = questionSet;
    }

    public Calendar getExamStartTime() {
    return examStartTime;
    }

    public void setExamStartTime(Calendar examStartTime) {
    this.examStartTime = examStartTime;
    }

    public int getMinScore() {
    return minPassScore;
    }

    public void setMinScore(int minScore) {
    this.minPassScore = minScore;
    }

    public void setMaxScore(int maxScore) {
    this.maxScore = maxScore;
    }

    public Calendar getExamEndTime() {
    return examEndTime;
    }

    public void setExamEndTime(Calendar examEndTime) {
    this.examEndTime = examEndTime;
    }

    public void setScore(int score) {
    this.score = score;
    }

    public String[] getInputAnswers() {
    return userInputAnswers;
    }

    public void setInputAnswers(String[] inputAnswers) {
    this.userInputAnswers = inputAnswers;
    }

    public boolean save(String fileName) {
    boolean flag = true;
    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    try {
    fos = new FileOutputStream(fileName.trim());
    out = new ObjectOutputStream(fos);
    out.writeObject(this);
    out.close();
    System.out.println("Exam Attempt Object Saved");
    } catch (IOException ex) {
    ex.printStackTrace();
    flag = false;
    }
    return flag;
    }

    public ExamAttempt load(String fileName) {
    ExamAttempt examAttempt = new ExamAttempt();
    FileInputStream fos = null;
    ObjectInputStream in = null;
    try {
    fos = new FileInputStream(fileName.trim());
    in = new ObjectInputStream(fos);
    examAttempt = (ExamAttempt) in.readObject();
    in.close();
    } catch (IOException ex) {
    ex.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    return examAttempt;
    }

    }




    ExamAttemptInterface.java
    ---------------------------
    package session14;

    import java.util.Collection;

    public interface ExamAttemptInterface {

    public String getStudentName();

    public String getExamType();

    public Collection<Question> getQuestionSet();

    public String[] getAnsForQuestion(Question question);

    public int getScore();

    public int getMinPassScore();

    public int getMaxScore();

    public int getTimeTaken();
    }



    QuestionBankJDBC.java
    -----------------------
    package session14;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;

    public class QuestionBankJDBC {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    Connection con = DerbyConnection.getConnection("OnlineExam");
    QuestionBank qBank= new QuestionBank();
    System.out.println(qBank.saveToDB(con));
    System.out.println(qBank.loadFromDB(con));
    System.out.println("Connected");

    }

    }
    Last edited by smartboy3k; 12-31-2008 at 04:41 PM. Reason: for self evaluation

  2. #2
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    First of all, only use getConnection() in the JSP code. Don't create connections in the JSP. Make sure getConnection is in its own class.

    Second, your approach should work, but it will be very slow. Opening connections takes a long time. Also, if you don't close every connection when you are done with them in the JSP, you will end with a too many connections error.

    Ideally, you create a connection and then hand it out each time getConnection() is called. The problem is, your Web server has multiple threads, so you have to make sure they wait their turn to use the connection. You will need an in-use flag, plus you will have to avoid thread issues. Look at the synchronized keyword, which will do that automatically, when setting the flag. The object in the synchronized operation can be anything, like "final Object mySyncObject = new Object();". You JSP will also have to call releaseConnection() when it is done using it, so the next thread can have its turn.

    Ideally, you could create multiple connections and pool them, but that's a year or two down the road.

    Here's what I learned the hard way. Put as *little* code in the JSP as possible. Create classes to do everything you can. Struts is a framework that enables you to do that, but it takes time to learn how it works.

    I know this seems painful, but do it right the first time, and you will save yourself an enormous amount of time and grief.

Similar Threads

  1. Replies: 4
    Last Post: 09-07-2010, 06:51 AM
  2. Replies: 0
    Last Post: 10-31-2008, 07:07 PM
  3. I m unable to connect one frame 2 the other
    By ankitraghuvanshi in forum NetBeans
    Replies: 2
    Last Post: 10-23-2008, 02:24 AM
  4. Is there a problem with Derby?
    By orion_mcl in forum Advanced Java
    Replies: 0
    Last Post: 08-10-2007, 04:35 AM
  5. Replies: 1
    Last Post: 07-23-2007, 11:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •