How to query database postgres from web java

Asked

Viewed 44 times

1

I want to do a database search from my HTML page by typing the first letters (eg and%) and in the table should appear the list of words starting with the typed letter: My database is Postgresql.

<form action="palavraServlet" method="post">

                <label>SearchidPal</label> 
                <input type="text" name="idpalsearch" id="idpalsearch" value="${user.idpal}"> 
                <label>SearchPal</label> 
                <input type="text" name="palsearch"  id="palsearch" value="${user.pal}">
                <input type="submit" value="Search">

            </form>

My Servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //doGet(request, response);
        String pal = request.getParameter("palsearch");
        BeanCursoJsp usuario = new BeanCursoJsp();
        usuario.setPal(pal);  
        daoAngpor.searchPalavra(usuario);

        RequestDispatcher view = request.getRequestDispatcher("/palavra.jsp");
        try {
            request.setAttribute("usuarios", daoAngpor.listarPalavra());
            view.forward(request, response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } 

my Dao:

public void searchPalavra(BeanCursoJsp usuario) {

        try {
        String sql = "select * from palavra where pal like ?%";
        PreparedStatement search = connection.prepareStatement(sql);
        search.setString(1, usuario.getPal());
        //search.execute();
        connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }


    }

And here it returns the full list by daoAngpor.listPalavra() but I just want the result of my search to appear in the table.

public List<BeanCursoJsp> listarPalavra() throws Exception  {
        List<BeanCursoJsp> listarPalavra = new ArrayList<BeanCursoJsp>();

        String sql = "select * from palavra";

        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {

        BeanCursoJsp beanCursoJsp = new BeanCursoJsp();
        beanCursoJsp.setIdpal(resultSet.getInt("idpal"));
        beanCursoJsp.setPal(resultSet.getString("pal"));

        listarPalavra.add(beanCursoJsp);

        }

        return listarPalavra;

        } 


No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.