2014-09-16 2 views
0

Java EE부터 시작하여 Java EE 용 Eclipse에서 간단한 프로젝트를 설정합니다. 이 구조는 전통적인 Java 웹 프로젝트 기본값입니다. Eclipse와 통합 된 Tomcat 및 일부 기본 서블릿입니다.Java 웹 응용 프로그램을 실행할 때 SQLException이 발생했습니다.

세부 사항 : 연락처를 대표하는이 클래스가 있습니다 : 패키지 br.myagenda.data;

import java.util.Calendar; 

public class Contato { 
    private long _id; 
    private final String _nome; 
    private final String _endereco; 
    private final String _email; 
    private final Calendar _dataNascimento; 

    public Contato(String nome, String endereco, String email, Calendar dataNascimento)  
    { 
     _nome = nome; 
     _endereco = endereco; 
     _email = email; 
     _dataNascimento = dataNascimento; 
    } 

    public void setId(long id) { 
     _id = id; 
    } 

    public long getId() { 
     return _id; 
    } 

    public String getNome() { 
     return _nome; 
    } 

    public String getEndereco() { 
     return _endereco; 
    } 

    public String getEmail() { 
     return _email; 
    } 

    public Calendar getDataNascimento() { 
     return _dataNascimento; 
    } 

그리고 이것은 SQL에서 위 클래스의 인스턴스를 번역하는 다른 클래스의 일부입니다 수입 br.myagenda.data.Contato; import br.myagenda.util.SqlConnectionFactory;

public class ContatoDAO { 
private final Connection _connection; 

public ContatoDAO() { 
    _connection = SqlConnectionFactory.getConnection(); 
} 

public void add(Contato contato) { 
    String sqlStatement = "INSERT INTO contatos (nome, email, endereco, data_nascimento)" 
      + "VALUES (?,?,?,?)"; 

    PreparedStatement statemant = null; 
    try {   
     statemant = _connection.prepareStatement(sqlStatement);   
     statemant.setString(1, contato.getNome()); 
     statemant.setString(2, contato.getEmail()); 
     statemant.setString(3, contato.getEndereco()); 

     Date dataParaGravar = new Date(Calendar.getInstance().getTimeInMillis()); 
     statemant.setDate(4, dataParaGravar); 
     statemant.execute(); 
     statemant.close();   
    } catch(SQLException e) { 
     throw new RuntimeException(e); 
    } 
} 
... 

명백한 이유로 위 클래스 메서드를 호출하는 "ContatoDaoTest"라는 기본 메서드가있는 클래스입니다.

재미있는 점은 다음과 같습니다. 테스트 클래스 (일반 Java 응용 프로그램으로 실행)를 실행하면 클래스가 데이터베이스에 액세스합니다.

그러나 양식을 채울 페이지와 사용자 입력을 저장하는 서블릿을 표시하는 HTML 페이지가 있습니다. 기본적으로 페이지 방문자 페이지는 연락처를 등록하기 때문에 내부적으로 서블릿은 Contato와 ContatoDAO를 인스턴스화하여 데이터베이스에 저장합니다.

<!DOCTYPE html SYSTEM "html.dtd"><html> 
<head> 
    <title>MyAgenda --- Adicionar um contato</title> 
</head> 
    <body> 
     <form action="addContact"> 
      Nome: <input type="text" name="nome"/><br /> 
      E-Mail: <input type="text" name="email"/><br /> 
      Endereço: <input type="text" name="address" /><br /> 
      Data Nascimento: <input type="text" name="dataNascimento" /><br /> 
      <input type="submit" value="Gravar" /> 
     </form> 
    </body> 
</html> 

그러나, 나는 "Gravar"버튼을 발사 할 때, 톰캣는 java.sql의가 있었다라는 오류 페이지를 보여줍니다되는 SQLException : 없음 적합한 드라이버를 찾을 수 없습니다!

질문은 다음과 같습니다. 일반적인 Java 응용 프로그램처럼 데이터베이스 액세스가 작동하지만 Java 웹 응용 프로그램으로 작동하지 않는 이유는 무엇입니까?

주 :

1

- MySQL의 커넥터가있는 WebContent/LIB 안에.

2 - 이클립스 빌드 경로에 mysql 커넥터 IS가 추가되었습니다.

3 - "가져 오기"를 통해 mysql 커넥터 내부 클래스에 액세스 할 수 있습니다.

추가 : 사실, 나는이에 대한 해결책을 찾았지만, 나는 이것이 매우 편리하지 느낌 :

고대 SqlConnectorFactory :

public class SqlConnectionFactory { 
    public static Connection getConnection() { 
     try { 
      return DriverManager.getConnection("jdbc:mysql://localhost/my_agenda", "root",  "senhadomysql"); 
     } catch(SQLException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

새로운 기능 :

public class SqlConnectionFactory { 
    public static Connection getConnection() { 
     try { 
      DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //this line made the diference. 
      return DriverManager.getConnection("jdbc:mysql://localhost/my_agenda", "root",  "senhadomysql"); 
     } catch(SQLException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 
+0

을 맞다면 웹 서버에 드라이버를 "설치"해야합니다. lib 폴더 안에 dll을 포함하면 충분하지 않습니다. – Steve

+0

당신은 정교 할 수 있습니까? 저는 JavaEE를 처음 접했습니다. – Sid

+0

미안하지만 나도 그다지 친숙하지 않다. 방금 서버 녀석에게 나 한테 해달라고 부탁 했어. 당신은 구글에 무슨 일이 일어나는지 볼 수 있습니다. – Steve

답변

0

왜 정상적인 Java 응용 프로그램으로 데이터베이스 액세스가 작동하지만 Java 웹 응용 프로그램으로 작동하지 않습니다?

Tomcat이 드라이버 com.mysql.jdbc.Driver를 찾을 수 없습니다.MySQL의 커넥터 - 자바와 함께 항아리 (your_tomcat)에 있어야합니다/lib 디렉토리 톰캣

당신이 링크를 볼 수 있습니다 자세한 내용은이

Class.forName("com.mysql.jdbc.Driver"); 
conn = DriverManager.getConnection(DB_URL,USER,PASS); 

과 같이 보여야 SqlConnectionFactory : http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm

관련 문제