Spring Boot Controller

Contents

@Controller and @RestController

@Controller
Return View, JSP, HTML, etc…

@RestController
JSON, XML etc… for Web API.

Example of Controller

@Controller
public class PageController {

	// Spring mvc @Controller
	//            @RestController
	
	@RequestMapping("/method1")
    public String method1() {
        return "/index.html";
    }
}

index.html

<html>
<head>
<title>Test</title>
</head>
<body>
<h3>Hello World!</h3>
</body>
</html>

index.html is under src/main/resources/public

Redirect, Forward

@Controller
public class PageController {
   @RequestMapping("/method1")
    public String method1() {
        return "/index.html";
    }
	
    @RequestMapping("/method2")
    public ModelAndView methods() {
	ModelAndView modelview = new ModelAndView();
	ServiceBean bean = new ServiceBean();
	bean.setId(1);
	bean.setName("Flex");
	modelview.addObject("data", bean);
	modelview.setViewName("/data.jsp");
	return modelview;
    }
	
    // Forward
    @RequestMapping("/forward1")
    public String forward1() {
        return "forward:method1";
    }
	
    // Redirect
    @RequestMapping("/redirect1")
    public String redirect1() {
        return "redirect:method1";
    }
	
    @RequestMapping("/redirect2")
    public String redirect2() {
        return "redirect:https://www.google.com.sg/";
    }
}

JSON Response

Jackson handle json response, and return bean json.

@RestController
public class ResController {

   // Return contents
   @RequestMapping("/json")
   public ServiceBean resBean() {
   	ServiceBean bean = new ServiceBean();
	bean.setId(2);
	bean.setName("Goo");
	return bean;
   }
}

bean

@Data
public class ServiceBean {
  private Integer id;
  private String name;
}