springMVC入门(四)------参数绑定与返回值类型

时间:2023-03-09 01:30:26
springMVC入门(四)------参数绑定与返回值类型

简介

从之前的介绍,已经可以使用springMVC完成完整的请求、返回数据的功能。

待解决的问题:如何将数据传入springMVC的控制器进行后续的处理,完成在原生servlet/jsp开发中HttpServletRequet的功能。

解决方案:springMVC参数绑定,即将客户端请求的数据绑定到处理器方法的形参上(也有特例,如Model、ModelMap、HttpServletResponse是返回)

默认的参数绑定

springMVC默认支持一下类型的参数绑定:

HttpServletRequest

HttpServletResponse

HttpSession

Model/ModelMap(本质一样,Model是接口、ModelMap是实现)

//此注解使得注解扫描器将此Controller加载进spring IOC容器进行管理
@Controller
public class UserController {
//此注解建立URL与此处理方法的映射关系
@RequestMapping("/queryUser")
public String queryUser(HttpServletRequest request, HttpServletResponse response
, HttpSession session, ModelMap model) {
String username = request.getParameter("username");
String email = request.getParameter("email");
//模拟后台数据
User user = new User();
user.setUsername(username);
user.setEmail(email);
//返回数据与视图
model.put("user", user);
return "/WEB-INF/jsp/user.jsp";
}
}
结果:

至此也引出了Controller方法返回值并不一定要是ModelAndView

Controller方法的返回值类型可为:

1、ModelAndView

2、String(可通过HttpServletRequest、Model/ModelMap返回数据)

3、void(可通过HttpServletResponse返回json数据)

简单数据类型的参数绑定

简单数据类型参数绑定成功的前提:jsp标签name属性名,与Controller方法的形参名一致

//此注解使得注解扫描器将此Controller加载进spring IOC容器进行管理
@Controller
public class UserController {
//此注解建立URL与此处理方法的映射关系
@RequestMapping("/queryUser")
public String queryUser(int id, String username, Model model) {
//模拟后台数据
User user = new User();
user.setUsername(username);
//返回数据与视图
model.addAttribute("user", user);
model.addAttribute("id", id);
return "/WEB-INF/jsp/user.jsp";
}
}

jsp页面增加id输出

<h2>Hello World!</h2>
${user.username}<br/>
${user.email}
${id}

结果:

POJO参数绑定

POJO数据类型参数绑定成功的前提:客户端请求的key/value数据,key的值与POJO字段名一致

//此注解使得注解扫描器将此Controller加载进spring IOC容器进行管理
@Controller
public class UserController {
//此注解建立URL与此处理方法的映射关系
@RequestMapping("/queryUser")
public ModelAndView queryUser(User user) {
//模拟后台数据
//返回数据与视图
return new ModelAndView("/WEB-INF/jsp/user.jsp").addObject("user", user);
}
}

结果:

包装POJO的参数绑定

包装POJO数据类型参数绑定前提:jsp标签name属性名要按照javabean的层级结构命名

    @RequestMapping("/addAuthority")
public ModelAndView addAuthority(User user) {
//模拟后台数据
//返回数据与视图
user.getAuthority().setId(user.getAuthority().getId() + 10);
user.getAuthority().setDescription(user.getAuthority().getDescription() + "abcd");
return new ModelAndView("/index.jsp").addObject("user", user);
}
public class User {
private String username;
private String email;
private UserAuthority authority; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public UserAuthority getAuthority() {
return authority;
} public void setAuthority(UserAuthority authority) {
this.authority = authority;
}
}
public class UserAuthority {
private String id;
private String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

JSP页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<h2>Hello World!</h2>
</body>
<form action="${request.getServletContext().getServletPath()}/springMVC/addAuthority.action" method="post">
<!-- 注意name名称 -->
权限编码:<input name="authority.id" type="text" value="${user.authority.id}"/><br/>
权限描述:<input name="authority.description" type="text" value="${user.authority.description}"/><br/>
<input type="submit" value = "提交"/>
</form>
</ht>

结果:

数组的参数绑定

数据参数绑定成功前提:jsp标签name属性值与Controller形参名一致

 @RequestMapping("/addArray")
public ModelAndView addArray(String[] names) {
//模拟后台数据
//返回数据与视图
if(null != names) {
for(int i = 0 ; i < names.length ; i++) {
names[i] = names[i] + " 2B";
}
}
return new ModelAndView("/index.jsp").addObject("names", names);
}

JSP页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<h2>Hello World!</h2>
</body>
<form action="${request.getServletContext().getServletPath()}/springMVC/addArray.action" method="post">
<input type="text" name="names" /><br/>
<input type="text" name="names" />
<input type="submit" value="提 交"/>
</form>
用户:
<c:forEach items="${names}" var="name">
${name}<br/>
</c:forEach>
</html>

结果:

List类型的参数绑定

List类型绑定成功的前提:必须通过POJO包装类接收List类型

 @RequestMapping("/addUser")
public ModelAndView addUser(User user) {
System.out.println(JsonUtils.objectToJsonString(user));
return new ModelAndView("/index.jsp");
}
public class User {
private String username;
private String email;
private List<UserAuthority> authorities; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public List<UserAuthority> getAuthorities() {
return authorities;
} public void setAuthorities(List<UserAuthority> authorities) {
this.authorities = authorities;
}
}

JSP页面:

<html>
<body>
<h2>Hello World!</h2>
</body>
<form action="${request.getServletContext().getServletPath()}/springMVC/addUser.action" method="post">
<table frame="border">
<tr>
<th>用户名</th>
<td><input type="text" name="username"/></td>
<th>email</th>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td colspan="2">权限编码</td>
<td colspan="2">权限描述</td>
</tr>
<tr>
<td colspan="2"><input type="text" name="authorities[0].id"/></td>
<td colspan="2"><input type="text" name="authorities[0].description"/></td>
</tr>
<tr>
<td colspan="2"><input type="text" name="authorities[1].id"/></td>
<td colspan="2"><input type="text" name="authorities[1].description"/></td>
</tr>
</table>
<input type="submit" value = "提交"/>
</form>
</html>

结果:

Map类型的参数绑定

Map类型绑定成功的前提:必须通过POJO包装类接收Map类型

@RequestMapping("/addUser")
public ModelAndView addUser(User user) {
System.out.println(JsonUtils.objectToJsonString(user));
return new ModelAndView("/index.jsp");
}
public class User {
private String username;
private String email;
private Map<String, String> authorities; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Map<String, String> getAuthorities() {
return authorities;
} public void setAuthorities(Map<String, String> authorities) {
this.authorities = authorities;
}
}

结果:

JSP页面

<html>
<body>
<h2>Hello World!</h2>
</body>
<form action="${request.getServletContext().getServletPath()}/springMVC/addUser.action" method="post">
<table frame="border">
<tr>
<th>用户名</th>
<td><input type="text" name="username"/></td>
<th>email</th>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>权限编码</td>
<td><input type="text" name="authorities[id]"/></td>
<td>权限描述</td>
<td><input type="text" name="authorities[description]"/></td>
</tr>
</table>
<input type="submit" value = "提交"/>
</form>
</html>

其它知识点

1、springMVC使用Converter(老版本中使用PropertyEditor)进行请求数据到参数绑定数据之间的类型转换

springmvc提供了很多Converter,特殊情况下需要使用自定义Converter(比如对日期数据的绑定)

此时需自定义转换类,并实现Convert<S,T>接口,并在配置文件中进行注册

2、有时界面标签name值与形参字段名不一致时,可以通过@RequestParam注解建立映射关系

通过required属性可指定参数是否必须传入

通过defaultValue属性可指定默认值