javamysqlthymeleafspark-framework

Deleting user from database in Spark Framework and Thymeleaf with MySQL


I have set up spark framework and thymeleaf with MySQL database. I am having trouble passing the id of user to be deleted to the backend of my application.

Backend

get("/delete", (rq, rs) -> {
        map.put("lista", studentService.getAllStudents());
        return thymeleafTemplateEngine.render(new ModelAndView(map,"delete"));});

delete("/delete:id", (rq, rs) -> {
           studentService.deleteStudent(rq.params(":id"));
           return "Korisnik uspesno izbrisan iz baze.";
        });

Service

public void deleteStudent(String id){
    sql = "DELETE FROM student WHERE student_id="+id;
    con = ConnectionManager.getConnection();
    try{
        stmt = con.createStatement();
        stmt.executeUpdate(sql);
    } catch (SQLException e){
        e.printStackTrace();
    }
}

Frontend

<form th:method="delete">
  <input th:name="id" type="text" placeholder="Id korisnika">
  <button type="submit">Submit</button>
</form>

This is the url that gets passed from thymeleaf template http://localhost:4567/delete?id=15, and i want it to be registered by spark frameworks delete method, is there some way I could accomplish this?


Solution

  • Backend

    delete("/delete/deleteStudent", (rq, rs) -> {
           studentService.deleteStudent(rq.queryParams("id"));
           map.put("lista", studentService.getAllStudents());
           return thymeleafTemplateEngine.render(new ModelAndView(map, "delete"));
        });
    

    Service

    public void deleteStudent(String id){
        System.out.println("Delete Called");
        sql = "DELETE FROM student WHERE student_id="+id;
        con = ConnectionManager.getConnection();
        try{
            stmt = con.createStatement();
            stmt.executeUpdate(sql);
        } catch (SQLException e){
            e.printStackTrace();
        }
    }
    

    Frontend

    <form th:method="delete" th:action="@{delete/deleteStudent}">
        <input type="number" th:name="id">
        <button type="submit">Delete user</button>
    </form>
    

    The problem was that i didn't know that if you want to make a delete request in your browser you need an XMLHttpRequest, so when i installed RESTClient plugin for firefox and sent delete request to my server, everything was working alright.