在Spring MVC中, @RequestParam 注解用于讀取表單數(shù)據(jù)并將其自動綁定到其中的參數(shù)提供的方法。因此,它忽略了 HttpServletRequest 對象讀取提供的數(shù)據(jù)的要求。
包括表單數(shù)據(jù),它還將請求參數(shù)映射到查詢參數(shù)以及多部分請求中的部分。如果方法參數(shù)類型為Map并且指定了請求參數(shù)名稱,則將請求參數(shù)值轉換為Map,否則將使用所有請求參數(shù)名稱和值填充map參數(shù)。
我們創(chuàng)建一個包含用戶名和密碼的登錄頁面。在這里,我們使用特定的值來驗證密碼。
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.1.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency>
這是從用戶接收名稱和密碼的登錄頁面。
index.jsp
<html> <body> <form action="hello"> UserName : <input type="text" name="name"/> <br><br> Password : <input type="text" name="pass"/> <br><br> <input type="submit" name="submit"> </form> </body> </html>
在控制器類中:
@RequestParam用于讀取用戶提供的HTML表單數(shù)據(jù)并將其綁定到request參數(shù)。 模型包含請求數(shù)據(jù)并提供給查看頁面。
HelloController.java
package com.nhooo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class HelloController { @RequestMapping("/hello") //讀取提供的表單數(shù)據(jù) public String display(@RequestParam("name") String name,@RequestParam("pass") String pass,Model m) { if(pass.equals("admin")) { String msg="Hello "+ name; //向模型添加消息 m.addAttribute("message", msg); return "viewpage"; } else { String msg="Sorry "+ name+". You entered an incorrect password"; m.addAttribute("message", msg); return "errorpage"; } } }
要運行此示例,以下視圖組件必須位于WEB-INF/jsp目錄中。
viewpage.jsp
<html> <body> ${message} </body> </html>
errorpage.jsp
<html> <body> ${message} <br><br> <jsp:include page="/index.jsp"></jsp:include> </body> </html> </html>
輸出: