I cannot consume Spring Boot Thymeleaf endpoints with ajax

tutusfun

I am creating a simple crud system using spring boot + thymeleaf.

I am stuck before I can not consume my spring endpoints with a simple ajax.

Controller

@Controller
public class StudentController {
  
   @Autowired
    private StudentService service;

    @GetMapping("/")
    public String viewHomePage(Model model) {
        List<Student> liststudent = service.listAll();
        model.addAttribute("liststudent", liststudent);
        System.out.print("Get / "); 
        return "index";
    }

}

index.html

function getall()
{
    $.ajax({

        url:"http://localhost:8080/Student/list",
        type: "GET",
        dataType: "JSON",
       success:function(data)
       {
          console.log(data);
       }
    });

}

I get a JSON error in web console.

What am I doing wrong?

JRichardsz
  • Thymeleaf is a server rendering framework, so ajax is not one of your priorities.
  • Thymeleaf + spring boot, returns html in any invocation.
  • If you want to load some data using javascript (ajax), your spring must expose another endpoints which returns a valid json response.
  • Decouple your spring controllers in two: views and rest endpoints

Rest Endpoints

@RestController
@RequestMapping("Student")
public class StudentController {

@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<Student> listStudents() {
    List<Student> liststudent = service.listAll();
    return liststudent;
}

Html Endpoints(spring + thymeleaf)

@Controller
@RequestMapping({ "/", "/index" })
public class ViewController {

@GetMapping
public String viewHomePage(Model model) {
    return "index";
}
  • assets must be inside src/main/resources/static folder if you are using thymeleaf framework

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related