Spring mvc Controller和RestFul原理解析

2020-03-19 12:01:11于海丽

控制器Controller

控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。 控制器负责解析用户的请求并将其转换为一个模型。 在Spring MVC中一个控制器类可以包含多个方法 在Spring MVC中,对于Controller的配置方式有很多种

实现Controller接口

Controller是一个接口,在org.springframework.web.servlet.mvc包下,接口中只有一个方法;

//实现该接口的类获得控制器功能
public interface Controller {
  //处理请求且返回一个模型与视图对象
  ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}

测试

编写一个Controller类,ControllerTest1

// 定义控制器
// 注意点:不要导错包,实现Controller接口,重写方法;
public class ControllerTest1 implements Controller {

  public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    //返回一个模型视图对象
    ModelAndView mv = new ModelAndView();
    mv.addObject("msg","Test1Controller");
    mv.setViewName("test");
    return mv;
  }
}

编写完毕后,去Spring配置文件中注册请求的bean;name对应请求路径,class对应处理请求的类

<bean name="/t1" class="com.xiaohua.controller.ControllerTest1"/>

编写前端test.jsp,注意在WEB-INF/jsp目录下编写,对应我们的视图解析器

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Kuangshen</title>
</head>
<body>
  ${msg}
</body>
</html>

配置Tomcat运行测试,我这里没有项目发布名配置的就是一个 / ,所以请求不用加项目名,OK!

说明:

实现接口Controller定义控制器是较老的办法

缺点是:一个控制器中只有一个方法,如果要多个方法则需要定义多个Controller;定义的方式比较麻烦;

使用注解@Controller

@Controller注解类型用于声明Spring类的实例是一个控制器(在讲IOC时还提到了另外3个注解);

Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描。

<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.xiaohua.controller"/>

增加一个ControllerTest2类,使用注解实现;

// @Controller注解的类会自动添加到Spring上下文中
@Controller
public class ControllerTest2{

  //映射访问路径
  @RequestMapping("/t2")
  public String index(Model model){
    //Spring MVC会自动实例化一个Model对象用于向视图中传值
    model.addAttribute("msg", "ControllerTest2");
    //返回视图位置
    return "test";
  }

}