上一篇我们学习了简单的参数接收方式,以及对编码的统一处理。今天我们来接收对象参数。
一、接收对象参数
jsp页面:
1<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
3<html>
4 <head>
5 <title>My JSP 'index.jsp' starting page</title>
6 </head>
7
8 <body>
9 <form action="${pageContext.request.contextPath }/user/login.do">
10 姓名:<input name="name" type="text" />
11 年龄:<input name="age" type="text" />
12 <input type="submit" value="注册" />
13 </form>
14 </body>
15</html>
Entity:
1package cn.wechatbao.entity;
2
3public class Student {
4 private String name;
5 private int age;
6//省略getter、setter
7}
Controller:
1@RequestMapping("/login.do")
2public ModelAndView login(Student student) throws Exception {
3 System.out.println("name="+student.getName());
4 System.out.println("age="+student.getAge());
5 ModelAndView mv = new ModelAndView();
6 mv.addObject("student", student);
7 mv.setViewName("/WEB-INF/jsp/success.jsp");
8 return mv;
9}
成功的提示页面(success.jsp):
1<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
3<html>
4 <head>
5 <title>SpringMVC1</title>
6 </head>
7
8 <body>
9 ${student }
10 </body>
11</html>
注意:整体接收需要表单的name属性值与实体的属性名一致。比如input的name为age,那么与之对应的实体类中,必须有一个age属性,并且该age属性需要有getter、setter方法。
二、域属性参数接收
域属性参数就是在A类中有一个为B类的属性。这时,我们对刚才的代码进行修改。新增School类。如下:
1public class School {
2 private String sname;
3 private String address;
4 //省略getter、setter
5}
修改Student类,如下:
1public class Student {
2 private String name;
3 private int age;
4 private School school;
5//省略getter、setter
6}
修改index.jsp页面的Form表单,如下:
1<form action="${pageContext.request.contextPath }/user/login.do">
2 姓名:<input name="name" type="text" />
3 年龄:<input name="age" type="text" />
4 学校名称:<input name="school.sname" type="text" />
5 学校地址:<input name="school.address" type="text" />
6 <input type="submit" value="注册" />
7</form>
三、接收路径变量
路径变量不作过多的介绍,只要了解就OK了。访问路径如下:
1http://localhost:8080/SpringMVC/user/zhangsan/24/register.do
Controller:
1@RequestMapping("/{name}/{age}/register.do")
2public ModelAndView register(@PathVariable String name,@PathVariable int age) throws Exception {
3 System.out.println("name="+name);
4 System.out.println("age="+age);
5 ModelAndView mv = new ModelAndView();
6 mv.addObject("name", name);
7 mv.addObject("age", age);
8 mv.setViewName("/WEB-INF/jsp/success.jsp");
9 return mv;
10}
注意:只是使用了一个@PathVariable的注解,该注解也可以指定name,如@PathVariable("pname")之类的。