研究一下SpringMVC提供的接收参数方式
1.方法中直接传入变量
变量直接接收,传入的变量名字和方法中的形参一致时默认可以接受;如果形参名字与传入变量名不一致,需要通过@RequestParam注解来给告诉传入的变量,传入哪个形参
TestController
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class TestController{
@RequestMapping("testParam1.do")
public String testParam1(@RequestParam("name")String username, String password){
return "welcome.jsp";
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="testParam1.do?name=klxh&password=123456">参数测试请求</a>
</body>
</html>
2.方法中直接传入实体对象
如果传递的参数可以组合成一个对象,那接收参数时可以用对象直接接收,但传递过来的变量名必须和对象的属性名一致;如果对象中还包含有其他对象,例如用户有一个钱包属性,钱包有颜色和装的钱数,那传入的变量名就要是钱包.颜色以及钱包.钱;若是集合,可用xxx[0].xxx、xxx[1].xxx表示
TestController
package controller;
import domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class TestController{
@RequestMapping("testParam1.do")
public String testParam1(User user){
System.out.println(user);
return "welcome.jsp";
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="testParam1.do" method="post">
name:<input type="text" name="name" value=""><br>
age:<input type="text" name="age" value=""><br>
sex:<input type="text" name="sex" value=""><br>
wallet-color:<input type="text" name="wallet.color" value=""><br>
wallet-money:<input type="text" name="wallet.money" value=""><br>
<input type="submit" value="submit">
</form>
</body>
</html>
3.方法中传入Map集合的方式
可以使用Map类型来接收请求的参数的
前提是 Map参数的前面 必须添加@RequestParam
否则Map是无法接收到参数的
4.方法中传递原生Request对象
直接在方法中传递参数变量即可接收
HttpServletRequest
HttpServletResponse