[springmvc]从前端获取参数以及显示
6.接收请求参数以及数据回显
接收普通参数
参数名与前端传递的参数名相同时
前端表单名name=name
<%--
Created by IntelliJ IDEA.
User: 塔塔
Date: 2022/7/25
Time: 13:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="/hello">
<p>username:<input type="text" name="name" placeholder="please print name:"></p>
<p><input type="submit" value="submit"></p>
</form>
</body>
</html>
后端收到的参数名String name
@RequestMapping("/hello")
public String hello(String name, Model md){
md.addAttribute("msg",name);
return "hello";
}
因此可以直接将前端的参数拿到
参数名与前端传递的参数名不同时或者有多个参数取一个时
-
名字相同时可以直接取到
@RequestMapping("/hello") public String hello(String name, Model md){ md.addAttribute("msg",name); return "hello"; }
-
在参数前面加上你要取得前端参数名称,就可以取到指定的数据
@RequestMapping("/hello")
public String hello(@RequestParam("name") String name, Model md){
md.addAttribute("msg",name);
return "hello";
}
@RequestMapping("/hello")
public String hello(@RequestParam("pwd") String name, Model md){
md.addAttribute("msg",name);
return "hello";
}
接收对象
前端数据与对象数据名严格匹配,不配时使用@RequestParam,传入的属性不对应时缺少的属性会为空。
对象实体类
package com.spring.pojo;
import lombok.Data;
/**
* @author panglili
* @create 2022-07-25-19:45
*/
@Data
public class User {
private String name;
private String pwd;
private int age;
private String email;
}
前端界面
<%--
Created by IntelliJ IDEA.
User: 塔塔
Date: 2022/7/25
Time: 13:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="/hello">
<p>username:<input type="text" name="name" placeholder="please print name:"></p>
<p>password:<input type="text" name="pwd" placeholder="please print pwd"></p>
<p>password:<input type="text" name="age" placeholder="please print age"></p>
<p>password:<input type="text" name="email" placeholder="please print email"></p>
<p><input type="submit" value="submit"></p>
</form>
</body>
</html>
后台接受
@RequestMapping("/hello")
public String hello(User user, Model md){
md.addAttribute("msg",user);
return "hello";
}
界面显示