zoukankan      html  css  js  c++  java
  • Springmvc:(三) Controller/ RestFul风格

    一、Contoller

    1. controller是一个接口,org.springframework.web.servlet.mvc

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

      使用注解方式

      1. @Controller注解类型用于声明Spring类的实例是一个控制器

      2. 使用扫描机制找到应用程序中所有基于注解的控制类,需要在配置文件中声明组件扫描

        <!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
        <context:component-scan base-package="com.ry.controller"/>
        
        @Controller
        public class ErrorController {
            @RequestMapping("/error")
            public String index(Model model) {
                Model model1 = model.addAttribute("msg", "1Controller");
        //        返回视图位置
                return "hello";
            }
        }
        
    3. @RequestMapper

      • @RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。
      • 用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

    二、RestFul风格

    1. 是一个资源定义和资源操作的风格,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存机制

    2. 功能

    • 资源:互联网所有的事物都可以被抽象为资源
    • 资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
    • 分别对应 添加、 删除、修改、查询。
    1. 使用RESTful操作资源 : 可以通过不同的请求方式来实现不同的效果!如下:请求地址一样,但是功能可以不同!

    2. //实现
      @Controller
      public class RestFulController {
          //映射访问路径
          @RequestMapping("/commit/{p1}/{p2}")
          public String index(@PathVariable int p1, @PathVariable int p2, Model model){
              int result = p1+p2;
              //Spring MVC会自动实例化一个Model对象用于向视图中传值
              model.addAttribute("msg", "结果:"+result);
              //返回视图位置
              return "test";        
          }    
      }
      

      @PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值

    3. restful风格的优点:

      • 使路径变得增加简洁
      • 获取参数更加方便,框架自动进行类型转换
      • 通过路径变量的类型约束访问参数
    4. 使用method属性可以约束请求的类型。GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE

      //映射访问路径,必须是POST请求
      @RequestMapping(value = "/hello",method = {RequestMethod.POST})
      public String index2(Model model){
          model.addAttribute("msg", "hello!");
          return "test";
      }
      

      总结:

      @RequestMapping注解能够处理HTTP 请求的方法

      @GetMapping是一个组合注解,相当于 @RequestMapping(method =RequestMethod.GET)

  • 相关阅读:
    [哈工大操作系统]一、环境配置
    [算法笔记]带权并查集
    C++:Reference to non-static member function must be called
    [算法笔记]并查集
    C++:string.size()比较问题
    [算法笔记]二分总结
    【LeetCode每日一题】2020.10.15 116. 填充每个节点的下一个右侧节点指针
    1Manjaro的安装
    【《你不知道的JS(中卷②)》】一、 异步:现在与未来
    【LeetCode每日一题】2020.7.14 120. 三角形最小路径和
  • 原文地址:https://www.cnblogs.com/dreamzone/p/12485651.html
Copyright © 2011-2022 走看看