Sunday, 25 February 2018

How to use controllers in a Spring web project ?


Make sure you have added dependency for a Web application
        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


EXAMPLE 1
Create a class with @Component and @RequestMapping annotations to indicating the path.
Use @GetMapping to serve by HTTP GET request and @ResponseBody to return response body with controller method.

@Component
@RequestMapping("hello")

public class EmpController {

   
    @GetMapping
    @ResponseBody

    public String hello() {
        return "Hello world";
    }

}

To access above controller, use : http://localhost:8080/hello
Since there is a single method defined with @GetMapping and @ResponseBody , it will be called.


EXAMPLE 2
@Component
@RequestMapping("hello")

public class EmpController2 {
   
    @GetMapping("rest")
    @ResponseBody

    public String hello() {
        return "hello";
    }

}

Here, we provided another path with the method also using @GetMapping("path")
To access above controller method, use http://localhost:8080/hello/rest


EXAMPLE 3
Instead of using @GetMapping, @PostMapping etc., you can use @RequestMapping by specifying path and method attributes.

@Component
@RequestMapping("hello")

public class EmpController2 {

   
    @RequestMapping(path="rest2", method=RequestMethod.GET)
    @ResponseBody

    public String hello2() {
        return "hello 2";
    }

}


You can access above method using : http://localhost:8080/hello/rest2

EXAMPLE 4
When you need a HTML page, instead of text from the controller method, DO NOT use @responseBody annotation and return a ModelAndView object.

@Component
@RequestMapping("hello")

public class EmpController2 {

    @GetMapping("html")
    public ModelAndView helloPg() {
        ModelAndView modelAndView = new ModelAndView("hello");
        modelAndView.addObject("name", "SHAAN");
        return modelAndView;
    }

}

You can access above method using : http://localhost:8080/hello/html
It will search and display : /src/main/resources/templates/hello.html

No comments:

Post a Comment

Note: only a member of this blog may post a comment.