SpringMVC笔记04 响应数据和结果视图
coconutnut

https://www.bilibili.com/video/BV1Sb411s7qa

P25~32

返回值类型

字符串

1
2
3
4
@RequestMapping("/testReturnString") 
public String testReturnString() {
return "success";
}

返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址

此处返回”success”将跳转到success.jsp

应用

从数据库中取User并存入Model

1
2
3
4
5
6
7
8
9
10
11
12
@RequestMapping("/testReturnString") 
public String testReturnString(Model model) {
// 模拟从数据库查询出User对象
User user = new User();
user.setUsername("ha");

// 存入Model
model.addAttribute("user",user);

// 跳转到success.jsp
return "success";
}

在success.jsp中取出User

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>

<h3>执行成功</h3>

${user.username}
${user.password}

</body>
</html>

void

1
2
3
@RequestMapping("/testVoid") 
public void testReturnString() {
}

如果没有返回值,默认根据请求路径跳转,如此处会找testVoid.jsp

修改需要用到Request、Response对象

1
2
3
4
5
@RequestMapping("/testVoid") 
public void testReturnString(HttpServletRequest request,HttpServletResponse response) throws Exception {
// 请求转发
request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
}

也可以用response重定向

1
2
3
4
5
// 例1
response.sendRedirect(request.getContextPath()+"index.jsp");

// 例2
response.sendRedirect("testRetrunString");

或者指定响应结果,例如响应json数据

1
response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8"); response.getWriter().write("HELLO");

ModelAndView

ModelAndView 是 SpringMVC 提供的一个对象

内部有一个Model,可以存数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RequestMapping("/testReturnModelAndView") 
public ModelAndView testReturnModelAndView() {
// 创建ModelAndView对象
ModelAndView mv = new ModelAndView();

// 模拟从数据库查询出User对象
User user = new User();
user.setUsername("ha");

// 可以存对象
mv.addObject("user",user);
// 也可以直接存键值对
mv.addObject("username", "张三");

// 指定跳转到哪个页面
mv.setViewName("success");

return mv;
}

转发和重定向

使用关键字进行转发和重定向时,无法使用视图解析器,需要自己写路径,用得不多

forward

1
2
3
4
@RequestMapping("/testForward") 
public String testForward() {
return "forward:/WEB-INF/pages/success.jsp";
}

路径必须写实际视图url,不能写逻辑视图

既可以转发到jsp,也可以转发到其他的控制器方法

redirect

1
2
3
4
5
@RequestMapping("/testRedirect") 
public String testRedirect() {
// return "redirect:/index.jsp"
return "redirect:testReturnModelAndView";
}

如果重定向到jsp页面,页面不能再WEB-INF中,会找不到

响应json

使用@ResponseBody 注解实现将 controller 方法返回对象转换为 json 响应给客户端

在webapp目录下新建js文件夹,把jquery.main.js复制进去,要用的jsp中引入

response.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>

<script src="js/jquery.min.js"></script>

<script>
// 页面加载,绑定单击事件
$(function(){
$("#btn").click(function(){
alert("hello btn");
});
});

</script>

</head>
<body>

<button id="btn">发送ajax的请求</button>

</body>
</html>

然而此时在页面中点击按钮,不会有响应

因为虽然引入了jquery.min.js

但是在web.xml中配置的DispatcherServlet拦截路径”/“,也会拦截静态的资源文件

过滤静态资源

在springmvc.xml中配置

1
2
3
4
<!--前端控制器,哪些静态资源不拦截-->
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>

配置之后再点击按钮,就会有弹框了

发送ajax请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
// 页面加载,绑定单击事件
$(function(){
$("#btn").click(function(){
// 发送ajax请求
$.ajax({
// 编写json格式,设置属性和值
url:"user/testAjax",
contentType:"application/json;charset=UTF-8",
data:'{"username":"hehe","password":"123","age":30}',
dataType:"json",
type:"post",
success:function(data){
// data是服务器端响应的json数据
alert(data);
alert(data.username);
alert(data.password);
alert(data.age);
}
});
});
});
</script>

响应json格式数据

Springmvc 默认用 MappingJacksonHttpMessageConverter 对 json 数据进行转换,需要加入 jackson 的包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>

客户端发送的ajax请求,传的是json字符串,后端将其封装到user对象中

1
2
3
4
5
6
7
8
// 模拟异步请求响应
@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody User user){
// 响应,模拟查询数据库
user.setUsername("haha");
user.setAge(40);
return user;
}

加@ResponseBody,把user转成json