Spring教程-Spring MVC RequestParam 注解

Spring MVC RequestParam 注解
在Spring MVC中,@RequestParam 注解用于读取表单数据并自动绑定到提供方法中的参数。因此,它不需要使用 HttpServletRequest 对象来读取提供的数据。
除了包含表单数据外,它还可以将请求参数映射到查询参数和多部分请求中的部分。如果方法参数类型为 Map,并且指定了请求参数名称,则请求参数值将被转换为 Map,否则 Map 参数将被填充为所有请求参数名称和值。
Spring MVC RequestParam 示例
让我们创建一个包含用户名和密码的登录页面。在这里,我们将使用特定的值验证密码。
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. 创建请求页面
这是一个接收用户输入的用户名和密码的登录页面。
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. 创建控制器类
在控制器类中:
- 使用 @RequestParam 读取用户提供的 HTML 表单数据,并将其绑定到请求参数。
- 模型包含请求数据,并将其提供给视图页面。
HelloController.java
package cn.javatiku;
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")
//read the provided form data
public String display(@RequestParam("name") String name,@RequestParam("pass") String pass,Model m)
{
if(pass.equals("admin"))
{
String msg="Hello "+ name;
//add a message to the model
m.addAttribute("message", msg);
return "viewpage";
}
else
{
String msg="Sorry "+ name+". You entered an incorrect password";
m.addAttribute("message", msg);
return "errorpage";
}
}
}
4. 创建其他视图组件
为了运行此示例,以下视图组件必须位于 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>
在这些 JSP 视图文件中,${message}
是从控制器传递到模型的数据,用于显示欢迎消息或错误消息。<jsp:include>
标签用于将登录页面 index.jsp
包含在错误页面中,以提供一个返回登录页的链接。
输出:
通过浏览器访问部署在服务器上的应用程序,输入用户名和密码,将显示欢迎消息或错误消息。