参数传递
配置Spring MVC的编码过滤器
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!--初始化参数--> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <!--强制使用UTF-8编码--> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
接收零散参数:装配原则为传递参数名和方法接收参数名一致
model代表给页面传递的数据
public String formRequest( String userCoder, String userPwd, Model model){ System.out.println(userCoder+"\t"+userPwd); model.addAttribute("userCode",userCoder); return "welcome"; }
jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登陆</title> </head> <body> <form action="/fourth/fourthRequest" method="post"> 编号:<input type="text" name="user_id"/> 名字:<input type="password" name="user_name"/> <input type="submit" value="登陆"/> </form> </body> </html>
手动装配@RequestParam name代表页面发送的参数名字 required代表参数是否必须传递 false代表可以不传递,默认为true defaultValue代表默认
@Controller @RequestMapping(value = "/fourth") public class FourthController { @RequestMapping(value = "/formRequest") /** * 接收零散参数:装配原则为传递参数名和方法接收参数名一致 * 手动装配@RequestParam name代表页面发送的参数名字 required代表参数是否必须传递 false代表可以不传递,默认为true defaultValue代表默认 * model代表给页面传递的数据 */ public String formRequest(@RequestParam(name = "userCode",required = false,defaultValue = "王洪涛") String userCoder, @RequestParam(name = "userPwd",required = false)String userPwd, Model model){ System.out.println(userCoder+"\t"+userPwd); model.addAttribute("userCode",userCoder); return "welcome"; }
域属性自动装配
/** * 注入域属性 * @return */ private List<Teacher> teaList; private Teacher teacher;
对象自动装配
/** * 对象参数:传递的对象参数和对象中的属性名保持一致 * 域属性传递:传递参数为:域属性.属性名 * 集合参数传递:集合名[下标].属性名 */ @RequestMapping(value = "/fourthRequest") public String fourthRequest(UserInfo info){ System.out.println(info.toString()); return "welcome"; }
集合自动装配
teacher1:<input type="text" name="teaList[0].teacher_name"/>
teacher2:<input type="text" name="teaList[1].teacher_name"/>
RESTFUL风格的参数传递
/** * get请求时,如果需要传递数据,那么则不能使用以往方式?name=xxx&age=yy,但是现在要遵循restful风格,举例 xxx/yyy/zzz * 根据地址栏URL匹配拿值 使用@PathVariable(name=地址栏中的参数映射) * @param name * @param age * @return */ @RequestMapping(value = "/restfulRequest/{b}/{d}") public String restfulRequest(@PathVariable(name = "b") String name,@PathVariable(name = "d") String age){ System.out.println(name+"\t"+age); return "welcome"; }