@controller是Spring框架提供的注解.
@controller标识的类,代表控制器类.(控制层/表现层),这里的控制层里的所有方法都可以调用@Service标识的类.(业务逻辑层/ServiceImpl层)@Service标识的类中的方法可以继续调用@Resposity标识的接口实现类(DAO层/持久层)
Spring MVC框架的核心是
M(model):指模型
V(View):视图层
C(Controller):控制层.
M代表模型一般指service和DAO;
view代表视图一般指页面eg:jsp,html ftl等;
C代表控制器,比如springMVC 中的controller或struts2中的action 。
MVC其实我们正常理解应该是VMC:JSP/HTML页面数据–>控制器–>数据逻辑处理并持久化。
@Controller标记在一个类上还不能真正意义上说它就是SpringMVC的控制器,应为这个时候Spring还不认识它,这个时候需要把这个控制器交给Spring来管理(即在对应的Xml文件中配置)。
<context:component-scan base-package="com.baidu">
</context:component-scan>
通常applicationContext.xml文件里面配置好扫描器之后,
扫描器可以扫描"com.baidu"包和它子包下面的所有带有@Component、@Controller、@Service、@Resposity等组件,并把他们添加到IOC容器中,由IOC容器管理。
@Controller用于标记在一个类上,使用它标记的类就是一个SpringMVC的 Controller类,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了 @RequestMapping 注解。
@Controller只是定义了一个控制器类,而使用 @RequestMapping 注解的方法才是处理请求的处理器。
@RestController注解是Spring框架提供的注解(Spring4.0新增):
@RestController = Controller + @ResponseBody
RestController不需要跳转,只需要返回数据给URL页面.
Controller进行页面跳转
RestController类中的返回值,它是一个方便的注释,默认是JSON对象,相当于Controller里添加了ResponseBody
示例代码:
@RestController
public class EmployeeController {
Employee employee = new Employee();
@GetMapping("/employees/{name}")
public Employee getEmployeeInJSON(@PathVariable("name") String name) {
employee.setName(name);
employee.setEmail("employee1@genuitec.com");
return employee;
}
}