0

We have created SpringMVC application using Spring-Boot and Thymleaf. Now as per new requirement, I have to convert them to SPring-REST for external application consumption(AngularJS and Android App) without affecting the thymleaf pages.

Please assist.

Below is the sample code. Like this many controllers are there

@Controller
@RequestMapping(value = "/admin/register")
@SessionAttributes("roles")
public class AdminRegisterController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleRepository roleRepository;

    @ModelAttribute("user")
    public User constructUser() {
        return new User();
    }

    @ModelAttribute("roles")
    public List<Role> InitializeRoles() {
        return roleRepository.findAll();
    }

    // Display Register Page
    @RequestMapping
    public String showRegister(Model model) {
        model.addAttribute("current", "register");
        return "register";
    }

    // Inserting new User
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView doRegister(@Valid @ModelAttribute("user") User user, BindingResult result) {
        if (result.hasErrors()) {
            return new ModelAndView("register");
        }
        userService.save(user);
        RedirectView redirectView = new RedirectView("/admin/register?success=true");
        redirectView.setExposeModelAttributes(false);
        return new ModelAndView(redirectView);
    }


    @RequestMapping("/available")
    @ResponseBody
    public String available(@RequestParam String username) {
        User user = userService.findOne(username);
        Boolean available = userService.findOne(username) == null;
        return available.toString();
    }


}
  • I am afraid you cant do what you want, you cant use the same return value in a method to be rendered by thymeleaf (return HTML) and json, but if your business logic is correctly isolated in yours services, what you can do is create some rest controllers and add there all methods you need. – cralfaro Apr 11 '16 at 11:16

1 Answers1

0

You can use the javax.ws.rs api for doing that.

<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.0</version>
</dependency>

And use @RestController instead of simple @Controllers in your current code.

KayV
  • 12,987
  • 11
  • 98
  • 148
  • Yes..I want to use SpringREST...So i think its pretty straight forward. But only issue would be how to consume them in different apps as my methods doesnot return ResponseEntity rather it returns the String -> pagename of thymleaf. I will edit my question with sample code. – user5572128 Apr 11 '16 at 09:45