JSP 页面的转发和重定向

Spring MVC 默认以转发的形式响应 JSP,可以手动进行修改。
重定向

@RequestMapping("/restful/{id}/{name}")
public String restful(@PathVariable("id") Integer id,@PathVariable("name")
String name){
 System.out.println(id+"-"+name);
 return "redirect:/index.jsp"; }

设置重定向的时候不能写逻辑视图,必须写明资源的物理路径,如“redirect:/index.jsp”

转发

@RequestMapping("/restful/{id}/{name}")
public String restful(@PathVariable("id") Integer id,@PathVariable("name")
String name){
 System.out.println(id+"-"+name);
 return "forward:/index.jsp"; }

等同于

@RequestMapping("/restful/{id}/{name}")
public String restful(@PathVariable("id") Integer id,@PathVariable("name")
String name){
 System.out.println(id+"-"+name);
 return "index"; }

Spring MVC 数据绑定

数据绑定:在后台业务⽅法中,直接获取前端 HTTP 请求中的参数。
HTTP 请求传输的参数都是 String 类型的,Handler 业务方法中的参数是开发者指定的数据类型,int、Integer、Object,因此需要进行数据类型的转换。
Spring MVC 的 HandlerAdapter 组件会在执行 Handler 业务方法之前,完成参数的绑定,开发者直接使用即可。

基本数据类型

@RequestMapping("/baseType")
@ResponseBody
public String baseType(int id){
 return "id:"+id; }

客户端 HTTP 请求中必须包含 id 参数,否则抛出 500 异常,因为 id 不能为 null,同时 id 的值必须为数值且必须为整数,否则抛出 400 异常。

包装类

@RequestMapping("/packageType")
@ResponseBody
public String packageType(Integer id){
 return "id:"+id; }

如果 HTTP 请求中没有包含 id 参数,不会报错,id 的值就是 null,会直接返回 id:null 给客户端。但是如果 id = a 或者 id = 1.5,同样会抛出 400 异常,因为数据类型无法匹配。

可以给参数列表添加 @RequestParam 注解,可以对参数进行相关设置。

@RequestMapping("/packageType")
@ResponseBody
public String packageType(@RequestParam(value = "id",required =
true,defaultValue = "0") Integer id){
 return "id:"+id; }

value = “id”:将 HTTP 请求中名为 id 的参数与 Handler 业务方法中的形参进行映射。
required:ture 表示 id 参数必填,false 表示非必填。
defaultValue = “0”:表示当 HTTP 请求中没有 id 参数时,形参的默认值为 0。

数组

@RequestMapping("/arrayType")
@ResponseBody
public String arrayType(String[] names){
 StringBuffer stringBuffer = new StringBuffer();
 for (String str:names){
 stringBuffer.append(str).append(" ");
 }
 return "names:"+stringBuffer.toString();
}

POJO

package com.southwind.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class User {
 private Integer id;
 private String name;
 private Address address; }
package com.southwind.entity;
import lombok.Data;
@Data
public class Address {
 private Integer code;
 private String value; }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>Title</title>
</head> <body>
 <form action="/hello/add" method="post">
 <table>
 <tr>
 <td>编号:</td>
 <td>
 <input type="text" name="id"/>
 </td>
 </tr>
 <tr>
 <td>姓名:</td>
 <td>
 <input type="text" name="name"/>
 </td>
 </tr>
 <tr>
 <td>地址编号:</td>
 <td>
 <input type="text" name="address.code"/>
 </td>
 </tr>
 <tr>
 <td>地址信息:</td>
 <td>
 <input type="text" name="address.value"/>
 </td>
 </tr>
 <tr>
 <td>
 <input type="submit" value="提交"/>
 </td>
 </tr>
 </table>
 </form>
</body>
</html>
@RequestMapping(value = "/add",method = RequestMethod.POST)
@ResponseBody
public String add(User user){
 return user.toString();
}

解决响应时乱码问题,springmvc.xml 中配置转换器即可。

<mvc:annotation-driven>
 <!-- 消息转换器 -->
 <mvc:message-converters>
 <bean
class="org.springframework.http.converter.StringHttpMessageConverter">
 <property name="supportedMediaTypes" value="text/html;charset=UTF-
8"></property>
 </bean>
 </mvc:message-converters>
</mvc:annotation-driven>

List

Spring MVC 不支持 List 类型的直接转换,需要包装成 Object。
List 的自定义包装类。

package com.southwind.entity;
import lombok.Data;
import java.util.List;
@Data
public class UserList {
 private List<User> users; }

业务方法

@RequestMapping("/listType")
@ResponseBody
public String listType(UserList users){
 StringBuffer stringBuffer = new StringBuffer();
 for(User user:users.getUsers()){
 stringBuffer.append(user);
 }
 return "⽤户:"+stringBuffer.toString();
}

JSP

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html> <head>
 <title>Title</title>
</head> <body>
 <form action="/hello/listType" method="post">
 ⽤户1ID:<input type="text" name="users[0].id"/><br/>
 ⽤户1姓名:<input type="text" name="users[0].name"/><br/>
 ⽤户2ID:<input type="text" name="users[1].id"/><br/>
 ⽤户2姓名:<input type="text" name="users[1].name"/><br/>
 ⽤户3ID:<input type="text" name="users[2].id"/><br/>
 ⽤户3姓名:<input type="text" name="users[2].name"/><br/>
 <input type="submit" value="提交"/>
 </form>
</body>
</html>

需要注意的是 User 类⼀定要有无参构造函数,否则抛出异常。

JSON

JSP

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html> <head>
 <title>Title</title>
 <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
 <script type="text/javascript">
 $(function(){
 var user = {
 "id":1,
 "name":"张三"
 };
 $.ajax({
 url:"/hello/jsonType",
 data:JSON.stringify(user),
 type:"POST",
 contentType:"application/json;charset=UTF-8",
 dataType:"JSON",
 success:function(data){
 alert(data.id)
 alert(data.name)
 }
 })
 })
 </script>
</head> <body>
</body>
</html>

注意
JSON 数据必须⽤ JSON.stringify() 方法转换成字符串
contentType:“application/json;charset=UTF-8” 不能省略

业务方法

@RequestMapping("/jsonType")
@ResponseBody
public User jsonType(@RequestBody User user){
 System.out.println(user);
 user.setId(2);
 return user; }

@RequestBody 注解
读取 HTTP 请求参数,通过 Spring MVC 提供的 HttpMessageConverter 接口将读取的参数转为
JSON、XML 格式的数据,绑定到业务方法的形参。
@ResponseBody 注解
将业务方法返回的对象,通过 HttpMessageConverter 接口转为指定格式的数据,JSON、XML 等,响应给客户端。
需要使用组件结合 @RequestBody 注解将 JSON 转为 Java Bean,这里使用 FastJson,其优势时候如果属性为空就不会将其转为 JSON。

如何使用 FastJson

1、pom.xml 中添加 FastJson 相关依赖

<!-- fastjson -->
<dependency>
 <groupId>com.alibaba</groupId>
 <artifactId>fastjson</artifactId>
 <version>1.2.32</version>
</dependency>

2、springmvc.xml 中配置 FastJson。

<mvc:annotation-driven>
 <!-- 消息转换器 -->
 <mvc:message-converters>
 <bean
class="org.springframework.http.converter.StringHttpMessageConverter">
 <property name="supportedMediaTypes" value="text/html;charset=UTF-
8"></property>
 </bean>
 <!-- fastjson -->
 <bean
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
</bean>
 </mvc:message-converters>
</mvc:annotation-driven>
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐