Spring MVC RequestParam 注解

在Spring MVC中, @RequestParam 注解用于讀取表單數(shù)據(jù)并將其自動綁定到其中的參數(shù)提供的方法。因此,它忽略了 HttpServletRequest 對象讀取提供的數(shù)據(jù)的要求。

包括表單數(shù)據(jù),它還將請求參數(shù)映射到查詢參數(shù)以及多部分請求中的部分。如果方法參數(shù)類型為Map并且指定了請求參數(shù)名稱,則將請求參數(shù)值轉換為Map,否則將使用所有請求參數(shù)名稱和值填充map參數(shù)。

Spring MVC RequestParam示例

我們創(chuàng)建一個包含用戶名和密碼的登錄頁面。在這里,我們使用特定的值來驗證密碼。

1、將依賴項添加到pom.xml

    <!-- 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>

2、創(chuàng)建請求頁面

這是從用戶接收名稱和密碼的登錄頁面。

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>

3、創(chuàng)建控制器類

在控制器類中:

@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";
        }   
    }
}

4、創(chuàng)建其他視圖組件

要運行此示例,以下視圖組件必須位于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>

輸出:

Spring MVC RequestParam注釋
Spring MVC RequestParam注釋
Spring MVC RequestParam Annotation
Spring MVC RequestParam注釋

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清