日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

SpringMVC學習Controller注解以及restful風格

作者:理想- 更新時間: 2022-05-10 編程語言

4、Controller注解以及restful風格

4.1、控制器Controller

控制器復雜提供訪問應用程序的行為,通常通過接口定義或注解定義兩種方法實現。

控制器負責解析用戶的請求并將其轉換為一個模型。

在Spring MVC中一個控制器類可以包含多個方法

在Spring MVC中,對于Controller的配置方式有很多種。

下面介紹接口定義和注解定義兩種方式來定義Controller

4.2、實現Controller接口

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

public interface Controller {
//用于返回一個模型和視圖
	@Nullable
	ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
}

配置SpringMVC

配置文件只留下視圖解析器和路徑映射。

<bean id="internalResourceViewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
bean>

<bean id="/t1" class="com.princehan.controller.MyController"/>

配置web.xml


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  
  <servlet>
    <servlet-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc-servlet.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>
  
  
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
web-app>

編寫控制器

public class MyController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", "controller");
        modelAndView.setViewName("test");
        return modelAndView;
    }
}

編寫測試頁面

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

配置Tomcat啟動測試
在這里插入圖片描述
說明:

  • 實現接口Controller定義控制器是較老的辦法
  • 缺點是:一個控制器中只有一個方法,如果要多個方法則需要定義多個Controller;定義的方式比較麻煩;

4.3、注解實現 @Controller

@Controller注解類型用于聲明Spring類的實例是一個控制器(在講IOC時還提到了另外3個注解);

Spring可以使用掃描機制來找到應用程序中所有基于注解的控制器類,為了保證Spring能找到你的控制器,需要在配置文件中聲明組件掃描。

配置SpringMVC

<context:component-scan base-package="com.princehan.controller"/>
<mvc:annotation-driven/>

新建一個Controller,使用注解實現

@Controller
public class MyController2 {
    @RequestMapping("/t2")
    public String Controller1(Model model) {
        model.addAttribute("msg", "helloController");
        return "test";
    }
    @RequestMapping("/t3")
    public String Controller2(Model model) {
        model.addAttribute("msg", "helloController");
        return "test";
    }
}

其中@RequestMapping表示映射的路徑,可以放于方法的聲明之上,表示映射的路徑,也可以放在一個類名上,該類方法的映射名前將會自動加上類上的映射。例如:

@Controller
@RequestMapping("/t")
public class MyController2 {
    @RequestMapping("/t1")
    public String Controller1(Model model) {
        model.addAttribute("msg", "helloController");
        return "test";
    }
}

映射路徑為/t/t1

4.4、RestFul風格

概念

Restful就是一個資源定位及資源操作的風格。不是標準也不是協議,只是一種風格。基于這個風格設計的軟件可以更簡潔,更有層次,更易于實現緩存等機制。

功能

  • 資源:互聯網所有的事物都可以被抽象為資源
  • 資源操作:使用POST、DELETE、PUT、GET,使用不同方法對資源進行操作。
  • 分別對應 添加、 刪除、修改、查詢。

傳統方式操作資源 :通過不同的參數來實現不同的效果!方法單一,post 和 get

? http://127.0.0.1/item/queryItem.action?id=1 查詢,GET
? http://127.0.0.1/item/saveItem.action 新增,POST
? http://127.0.0.1/item/updateItem.action 更新,POST
? http://127.0.0.1/item/deleteItem.action?id=1 刪除,GET或POST

使用RESTful操作資源 : 可以通過不同的請求方式來實現不同的效果!如下:請求地址一樣,但是功能可以不同!

? http://127.0.0.1/item/1 查詢,GET
? http://127.0.0.1/item 新增,POST
? http://127.0.0.1/item 更新,PUT
? http://127.0.0.1/item/1 刪除,DELETE

上手測試

新建一個Controller

@Controller
public class RestfulController {
    @RequestMapping("/a1/{a}/{b}")
    public String test1(@PathVariable int a, @PathVariable int b, Model model) {
        int res = a + b;
        model.addAttribute("msg", "結果是" + res);
        return "test";
    }

    @GetMapping("/a2/{a}/{b}")
    public String test2(@PathVariable int a, @PathVariable String b, Model model) {
        String res = a + b;
        model.addAttribute("msg", "結果是" + res);
        return "test";
    }

    @RequestMapping(value = "/a3/{a}/{b}", method = {RequestMethod.GET})
    public String test3(@PathVariable int a, @PathVariable int b, Model model) {
        int res = a - b;
        model.addAttribute("msg", "結果是" + res);
        return "test";
    }
}

配置Tomcat并測試

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
通過@PathVariable注解來聲明路徑變量。

  • RestFul風格更加潔。
  • 獲得參數更加方便,框架會自動進行類型轉換。
  • 通過路徑變量的類型可以約束訪問參數,如果類型不一樣,則訪問不到對應的請求方法。

注意:使用瀏覽器地址欄進行訪問默認是Get請求,如果使用的是其他方式的請求,會報錯

使用@RequestMapping設置請求類型

在這里插入圖片描述

value 或者path屬性表示請求路徑。method 表示請求類型。

  @RequestMapping(value = "/a3/{a}/{b}", method = {RequestMethod.GET})
  public String test3(@PathVariable int a, @PathVariable int b, Model model) {
      int res = a - b;
      model.addAttribute("msg", "結果是" + res);
      return "test";
  }
}

在這里插入圖片描述
上圖表示可以選擇的請求類型。

小結:

Spring MVC 的@RequestMapping 注解能夠處理 HTTP 請求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。

所有的地址欄請求默認都會是 HTTP GET 類型的。

方法級別的注解變體有如下幾個: 組合注解

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

@GetMapping是一個組合注解

它相當于@RequestMapping(method =RequestMethod.GET)的一個快捷方式。

補充:
若一個類用@RestController注解修飾,則這類中的所有的請求都會被視圖解析器忽略。
若不想視圖解析器忽略掉所有的請求,可以不加@RestController,用@ResponseBody修飾方法,也可以起到同樣的效果。

原文鏈接:https://blog.csdn.net/weixin_51624761/article/details/124260671

欄目分類
最近更新