環境:SpringBoot3.3.0
在SpringBoot應用開發中,傳統的請求屬性處理方式如@ModelAttribute,@SessionAttribute,@RequestAttribute以及RedirectAttributes似乎用的越來越少了,但是在一些特定場景下它們發揮著不可或缺的作用尤其是當涉及到表單提交、會話狀態管理和重定向屬性傳遞時。
接下來將詳細接上上面幾個注解及類的使用。
該注解可用于方法參數及方法上;
@GetMapping("/product/{cateId}/{id}")public ProductDTO test(@ModelAttribute ProductDTO dto) { return dto ;}
圖片
首先,SpringMVC會自動將請求URI中的占位符數據綁定到當前ProductDTO對象上,這個綁定與@ModelAttribute注解沒有關系。而這里注解的作用是將當前ProductDTO對象綁定到模型數據中,接下來如果你使用的thymeleaf則可以直接在頁面中訪問,如下示例:
@GetMapping("/product/{cateId}/{id}")public String test(@ModelAttribute ProductDTO dto) { return "modelattribute" ;}
在頁面中直接訪問ProductDTO;
<div th:if="${productDTO}"> <ul> <li>cateId: <a th:text="${productDTO.cateId}"></a></li> <li>id: <a th:text="${productDTO.id}"></a></li> </ul></div>
圖片
在上面你看到了,默認訪問的key是當前類型的首字母改為小寫,我們可以通過配置屬性修改默認key
public String test(@ModelAttribute("dto") ProductDTO dto)
這樣在頁面中訪問的key將是:dto。
@GetMapping("/product/{cateId}/{id}")public String test() { return "modelattribute" ;}@ModelAttribute("dto")public ProductDTO dto(ProductDTO dto) { System.out.println("dto....") ; return dto ;}
將注解用于方法上后,當前的Controller中的所有接口都會先執行該方法將請求中的參數信息綁定到ProductDTO對象中,最后將該dto綁定到模型數據上。通過上面的配置你在頁面上一樣也可以訪問該對象數據。
該注解只能用于方法參數上。
該注解的作用用于讀取session中的數據到當前的參數中,如下示例:
@GetMapping("/user")@ResponseBodypublic User user(@SessionAttribute("user") User user) { return user ;}// 模擬登錄后將User對象存入Session中@GetMapping("/login")@ResponseBodypublic String login(HttpSession session) { session.setAttribute("user", new User(666L, "Admin")) ; return "login success" ;}
這里會讀取Session中key=user的數據到當前User對象中,你需要先登錄,然后再訪問/user接口。
如果session中沒有user,那么程序將會報錯
圖片
錯誤提示,session對象中沒有user屬性。通過如下方式設置不是必須的;
public User user(@SessionAttribute(value = "user", required = false) User user)
也可以將參數設置為Optional;
public User user(@SessionAttribute("user") Optional<User> user)
通過上面2中方式設置,在Session中不存在對應的屬性時也不會報錯。
注:還有一個@SessionAttributes注解,該注解可以用于類上。
該注解同樣只能用于方法參數上。
與 @SessionAttribute 類似,你也可以使用 @RequestAttribute 注解來訪問先前創建的請求屬性(例如,由 Servlet Filter或 HandlerInterceptor 創建的屬性),如下示例:
先定義一個Filter,該Filter作用是向Request中設置值;
@Componentpublic class UserFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { request.setAttribute("user", new User(888L, "Guest")) ; filterChain.doFilter(request, response) ; }}
接下來在Controller中通過@RequestAttribute訪問user屬性。
@GetMapping("/user")@ResponseBodypublic User user(@RequestAttribute("user") Optional<User> user) { return user.orElse(new User()) ;}
圖片
與@SessionAttribute一樣,參數可以通過Optional設置不是必須的。
當頁面通過redirect進行跳轉時,可以通過該類定義在接口方法參數中,將數據保存到該對象中后,你就可以在調整到的頁面中使用配置的屬性了,如下示例:
@GetMapping("")public String index(RedirectAttributes ra) { // 將你需要的數據存入該對象中 ra.addFlashAttribute("message", "hello") ; // redirect其它頁面 return "redirect:/page/tm" ;}@GetMapping("tm")public String tm(RedirectAttributes ra) { return "test" ;}
test.html頁面如下:
<body> <h1>Test Page</h1> <div th:if="${message}"> <h2 th:text="${message}" /> </div></body>
訪問上面的/page,將redirec到最終的test.html頁面;
圖片
redirect過來后我們可以訪問到配置的數據。
本文鏈接:http://www.tebozhan.com/showinfo-26-98547-0.html在SpringBoot項目中這幾個注解你們還用嗎?
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com