How do I change my controller into a REST controller? From Thymeleaf to Vue.js

Viewed 29

For my university project, I have an up and running SpringBoot project using Thymeleaf, but I would now like to use Vue.js instead for my front end. To do this, I am wanting to change my controllers into REST Controllers but I'm struggling with how to go about that.

Here is an example of a method within the controller:

public String showQuiz(@PathVariable String subject, Model model) {
        Session session = new Session();
        session.setStart_time(new Timestamp(System.currentTimeMillis()));
        List<Question> questions = questionService.getAllQuestionsBySubject(subject);
        Quiz quiz = new Quiz(subject, questions, session);
        session.setQuiz(quiz);
        session.setScore(0);
        ContextController.getEmployee().setSession(session);
        session.setEmployeeId(ContextController.getEmployee().getId());
        session.setEmployeeName(ContextController.getEmployee().getUsername());
        ContextController.setSession(session); //optional shared context
        sessionService.saveSession(session);
        ContextController.questions = questions;
        model.addAttribute("questions", questions);
        AnswersDTO answersDto = new AnswersDTO();
        model.addAttribute("answersDto", answersDto);
        model.addAttribute("employee", ContextController.getEmployee());
        return "quiz";
    }

How would I convert the code above to return JSON?

1 Answers

Annotate your controller class @RestController. Return your data object wrapped in a org.springframework.http.ResponseEntity.

return ResponseEntity.ok().body(myDataObject);
Related