SpringMVC-02-常用操作

四、RequestMapping与RESTful

4.1 @RequestMapping

  • @RequestMapping 注解用于将URL映射到一个控制器或者控制器中的一个方法上。如果作用在类上的话,访问地址就是类上的URL+方法上的URL

  • 作用在方法上,访问路径:/test

    @Controller
    public class TestController {
    
        @RequestMapping("/test")
        public String test1(Model model) {
            model.addAttribute("from", "TestController::test1()");
            model.addAttribute("msg", "test1");
            return "test";
        }
    
    }
    

    image-20201206143632009

  • 作用在类上,访问路径:/TestController/test

    @Controller
    @RequestMapping("/TestController")
    public class TestController {
    
        @RequestMapping("/test")
        public String test1(Model model) {
            model.addAttribute("from", "TestController::test1()");
            model.addAttribute("msg", "test1");
            return "test";
        }
    } 
    

    image-20201206145202457

4.2 RESTful风格

  • 什么是RESTful?

    • RESTful是一种设计风格,适用于网络应用程序
  • 特点

    • 每一个URL代表1种资源;
    • 客户端使用GET、POST、PUT、DELETE4个表示操作方式的动词对服务端资源进行操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源;
    • 通过操作资源的表现形式来操作资源;
    • 资源的表现形式是XML或者HTML;
    • 客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都必须包含理解请求所必需的信息。
    • 一句话
      • RESTful要求使用标准的HTTP方法对资源进行操作,所以URL只应该来表示资源的名称,而不应该包括资源的操作。 简单来说,URL不应该使用动作来描述
  • 传统的方式操作资源

  • RESTful

    • 使用RESTful操作资源,对资源的不同操作模式,是通过请求的不同方法实现的

4.3 SpringMVC中的RESTful

  • SpringMVC中,原生的支持RESTful设计。

  • 点开@RequestMapping的源码,可以看到其中有关于请求方法的字段。

    image-20201206150446570

  • 其中,RequestMethod 是一个枚举类,其中包含了 GETHEADPOSTPUTPATCHDELETEOPTIONSTRACE 等http的请求方法。

  • 如果要使用RESTful的话,只需要在注解上加上响应的请求方法进行限定即可

  • 例如

    @Controller
    public class TestController {
    
        @RequestMapping(value = "/test", method = RequestMethod.POST)
        public String test1(Model model) {
            model.addAttribute("from", "TestController::test1()");
            model.addAttribute("msg", "test1");
            return "test";
        }
    
    }
    

    image-20201206151126965

    • 在方法上限定了只能使用post方法去访问,那么我们使用普通的get方法就无法取得访问,要使用POST方法去请求才能正常访问

    image-20201206151301731

  • 实际上,@RequestMapping注解有许多衍生注解,他们直接限定了访问的方法,他们是

    • @GetMapping@PostMapping@PutMapping@DeleteMapping@PatchMapping
  • 示例

    @Controller
    public class DataController {
    
        @GetMapping("/t1/{id}/{name}")
        public String test1(@PathVariable int id, @PathVariable String name, Model model) {
            model.addAttribute("id", id);
            model.addAttribute("name", name);
            return "/test.jsp";
        }
    
    }
    

    image-20201206205855955

  • 只需要在参数名前加上 @PathVariable 注解即可使用路径作为参数进行传递


五、转发和重定向

5.1 ServletAPI

  • 通过设置ServletAPI , 不需要视图解析器
    • 通过HttpServletResponse实现重定向和转发
@Controller
public class Go {
    @RequestMapping("/result/redirect")
    public void sendRedirect(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
        // 重定向
        rsp.sendRedirect("/index.jsp");
    }
    
    @RequestMapping("/result/forward")
    public void forward(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
        // 转发
        req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req, rsp);
    }
}

5.2 SpringMVC

  • SpringMVC中可以通过前缀来支持重定向或者转发
    • 默认不加前缀时,转发
    • 前缀 forward: 表示转发,redirect: 表示重定向
@Controller
public class Go {
    @RequestMapping("/result/t1")
    public String test1() {
        return "forward:/index.jsp";
    }
    
    @RequestMapping("/result/t2")
    public String test2() {
        return "redirect:/index.jsp";
    }

}
  • 注意,在进行转发和重定向时,要注意视图解析器对URL的影响

六、数据处理

6.1 处理提交的数据

  • 基本类型数据
    
    @GetMapping("/t1")
    public String test1(@RequestParam("id") int id,@RequestParam("name") String name, Model model) {
        model.addAttribute("id", id);
        model.addAttribute("name", name);
        return "test.jsp";
    }
    

    image-20201206210124402

  • 对象

    • SpringMVC中,要求提交的表单域和对象的属性名一致 , 参数使用对象属性名即可提取

    • Controller

      @GetMapping("/t2")
      public String test2(User user, Model model) {
          model.addAttribute("user", user);
          return "test.jsp";
      }
      
    • 实体类

      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      public class User {
      
          private int id;
          private String name;
          private int age;
      
      }
      

  • 复杂类型数据

    • SpringMVC对于复杂类型的数据并不非常友好,因为对于复杂类型的数据,通常使用JSON、XML等格式进行传输,这里只简单介绍一下数组类型的。List等类型的数据,还需要进行包装,这无疑是多此一举的操作

    • 数组,要对数组类型进行绑定,只需要对一个参数传入多个值即可

      • Controller

        @RequestMapping("/t3")
        public String test3(String[] hobby, Model model) {
            model.addAttribute("value", Arrays.toString(hobby));
            return "test.jsp";
        }
        

  • 总结

    • 别指望通过URL向后端传递各种复杂的数据。SpringMVC处理简单类型的数据传出还可以,但是对于复杂类型的数据,还是老老实实的用Json去传吧

6.2 向View传递数据

  • Model

    • SpringMVC中的Model可以携带少量和简单的数据返回到前端,如

      @GetMapping("/t1")
      public String test1(@RequestParam("id") int id,@RequestParam("name") String name, Model model) {
          model.addAttribute("id", id);
          model.addAttribute("name", name);
          return "test.jsp";
      }
      
  • ModelMap

    • ModelMap继承了LinkedHashMap,这使得他具有Map的一些特性,优化了数据的封装过程
    • ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,他的作用类似于request对象的setAttribute方法的作用:用来在一个请求过程中传递处理的数据。
    @RequestMapping("/hello")
    public String hello(@RequestParam("username") String name, ModelMap model){
        //封装要显示到视图中的数据
        //相当于req.setAttribute("name",name);
        model.addAttribute("name",name);
        System.out.println(name);
        return "hello";
    }
    

6.3 处理乱码

  • SpringMVC中内置了一个过滤器,可以处理大多数情况下的乱码问题

  • 设置方法

    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
  • 注意:

    • /*/的区别
      • /* :会匹配任何请求
      • / :匹配任何请求,*.jsp 除外
posted @ 2020-12-06 22:17  PrimaBruceXu  阅读(136)  评论(0编辑  收藏  举报