Search code examples
spring-bootthymeleaf

Service layer doesn't delete entity?


I have a controller that must delete my entity:

@GetMapping ("/delete")
@PreAuthorize ("hasAuthority ('Admin')")
public String deleteStudent (Long studentId, String keyword) {
    studentService.removeStudent(studentId);
    return "redirect:/students/index?keyword="+keyword;
}

and HTML page that represent my entity:

<div class="container mt-3">
    <div class="card-header">List of Students</div>
    <div class="card-body">
        <table class="table mt-3">
            <thead>

                <tr class="text-center">
                    <th>Student Id</th>
                    <th>Student First Name</th>
                    <th>Student Last Name</th>
                    <th>Student Level</th>
                </tr>
            </thead>
            <tbody>
                <tr class="text-center" th:each="student: ${list}">
                    <td th:text="${student.getStudentId()}"></td>
                    <td th:text="${student.getFirstName()}"></td>
                    <td th:text="${student.getLastName()}"></td>
                    <td th:text="${student.getLevel()}"></td> 
                    <td> 
                    <a onclick="confirm ('Are you sure')" class="btn btn-danger"
                    th:href="@{students/delete(studentId=${student.getStudentId()}, keyword=${keyword})}"> Delete </a>
                    </td>
                </tr>
            </tbody>
        </table>

    </div>

My Service

public interface StudentService {
    void removeStudent (Long studentId);

I run application, open http://localhost:8071/students/index everything work okay, but when I delete my entity I'm getting:

ERROR PAGE There was an unexpected error (type=Not Found, status=404).

-> http://localhost:8071/students/students/delete?studentId=1&keyword=


Solution

  • You have students duplicated in the path, hence 404:

    http://localhost:8071/students/students/delete
    

    Your line

    th:href="@{students/delete(studentId=${student.getStudentId()}, keyword=${keyword})}"
    

    Should be:

    th:href="@{delete(studentId=${student.getStudentId()}, keyword=${keyword})}"