Difference between @Controller and @Rest Controller
@Controller
The @Controller annotation has been part of the framework for a very long time.@Controller annotation designates that the annotated class is a controller. It is a specialization of @Controller and is autodetected through classpath scanning. It is typically utilized in amalgamation with annotated handler methods predicated on the @RequestMapping annotation.
For example,
@Controller
@RequestMapping("users")
public class HomeController {
@GetMapping(produces = "application/json")
public @ResponseBody User getAllUsers() {
return findAllUsers();
}
}
The request handling method is annotated with @ResponseBody. This annotation enables automatic serialization of the return object into the HttpResponse.
@RestController
The @RestController annotation was introduced in Spring 4.0 to simplify the engenderment of RESTful web services. It's an convenience annotation that combines @Controller and @ResponseBody
For example,
@RestController
@RequestMapping("users")
public class HomeController {
@GetMapping(produces = "application/json")
public Book getAllUsers() {
return findAllUsers();
}
}
The controller is annotated with the @RestController annotation, consequently the @ResponseBody isn't required. Every request handling method of the controller class automatically serializes return objects into HttpResponse. Link
After conversion
RestController
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1")
public class TeacherController {
@Autowired
TeacherService teacherService;
@GetMapping("/teacher")
public List<Teacher> fetchAllTeacher() {
return teacherService.getAll();
}
}
HTML
<table id="table-content" border='1'>
<tr>
<th>Teacher ID</th>
<th>Teacher Name</th>
<th>Teacher Position</th>
</tr>
Javascript(Not tested)
var service = 'http://localhost/api/v1/';
$(document).ready(function(){
jQuery.support.cors = true;
$.ajax(
{
type: "GET",
url: service + '/teacher/',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var trHTML = '';
$.each(data, function (i, item) {
trHTML += '<tr><td>' + data.Teacher[i].Name + '</td><td>' + data.Teacher[i].Position + '</td></tr>';
});
$('#table-content').append(trHTML);
},
error: function (msg) {
alert(msg.responseText);
}
});
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…