網站首頁 編程語言 正文
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
相關推薦
- 2022-09-06 C語言常見排序算法歸并排序_C 語言
- 2022-05-10 Element-ui 中 Select 選擇器下拉框樣式及輸入框樣式的修改問題(背景色透明與懸停背景
- 2023-04-06 C++中的多態問題—理解虛函數表及多態實現原理_C 語言
- 2022-09-18 centos+nginx+uwsgi部署django項目上線_python
- 2022-05-09 輕量級ORM框架Dapper應用之實現DTO_實用技巧
- 2023-03-11 React中的for循環解讀_React
- 2022-06-18 C語言?從根本上理解指針_C 語言
- 2022-11-25 Go實現快速生成固定長度的隨機字符串_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支