PostgreSQL 9.4
Noticias()
. public static void main()
of class Noticias()
the call is made from a getConexao()
method; pagecontroller?=p=noticias
in the browser it returns me java.lang.NullPointerException
. Noticias()
class in Eclipse it does not return a
pointer null and makes connection to the database without any error. Note: Inside the WebContent / WEB-INF / lib / directory I'm with lib postgresql-9.4-1201.jdbc4.jar but anyway when I use my class Noticias()
browser is not connected to the database, my Tomcat server is running through the Eclipse IDE.
public class PageController extends HttpServlet {
private static final long serialVersionUID = 1L;
public PageController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Chamou o metodo GET");
String pagina = request.getParameter("p");
if (pagina.equals("noticias")){
Noticias noticias = new Noticias();
List<Noticias> lista = noticias.getNoticias();
request.setAttribute("noticias", lista);
RequestDispatcher saida = request.getRequestDispatcher("noticias.jsp");
saida.forward(request, response);
}
}
Follow class Noticias()
:
public class Noticias{
int grid;
String topico;
String conteudo;
int usuario;
Date data;
public Noticias(){
}
public static void main(String[] args) {
List<Noticias> noticias = getNoticias();
}
public static List<Noticias> getNoticias(){
List<Noticias> noticia_list = new ArrayList<Noticias>();
String sql = "SELECT * from NOTICIAS";
Connection conexao = null;
try {
conexao = DriverManager.getConnection("jdbc:postgresql://localhost:5432/base", "postgres", "postgres");
System.out.print("Conexao com o banco de dados efetuada com sucesso!");
} catch (SQLException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Erro durante a conexao com o banco de dados!");
}
PreparedStatement prepared_sql = null;
try {
prepared_sql = conexao.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
try {
ResultSet result = prepared_sql.executeQuery();
while(result.next()){
Noticias noticia = new Noticias();
noticia.setGrid(result.getInt("grid"));
noticia.setTopico(result.getString("topico"));
noticia.setConteudo(result.getString("conteudo"));
noticia.setUsuario(result.getInt("usuario"));
noticia.setData(result.getDate("data"));
noticia_list.add(noticia);
}
} catch (SQLException e) {
e.printStackTrace();
}
return noticia_list;
}