🍁博客主页:👉 不会压弯的小飞侠
✨欢迎关注:👉点赞👍收藏⭐留言✒✨如果觉得博主的文章还不错的话,请三连支持一下博主。
🔥欢迎大佬指正,一起 学习!一起加油!
一、数据响应方式
页面跳转
- 直接返回字符串
- 通过ModelAndView对象返回
回写数据
- 直接返回字符串
- 返回对象或集合
二、页面跳转
1.直接返回字符串
- 直接返回字符串:此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转。
- 返回带有前缀的字符串:
- 转发: forward:/WEB-INE/views/ index.jsp
- 重定向: redirect : / index.jsp
在SpringMVC快速入门已演示:
快速入门案例
2.通过ModelAndView对象返回
1.方式一
@RequestMapping(value = "/quick2")
public ModelAndView save2(){
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("userName","小飞侠");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
运行测试:
2.方式二
@RequestMapping(value = "/quick3")
public ModelAndView save3(ModelAndView modelAndView){
//设置模型数据
modelAndView.addObject("userName","小马哥");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
运行测试:
3.方式三
@RequestMapping(value = "/quick4")
public String save4(Model model){
//设置模型数据
model.addAttribute("userName","马奎斯");
return "success";
}
运行测试:
4.方式四(不常用)
@RequestMapping(value = "/quick5")
public String save5(HttpServletRequest hsr){
//设置模型数据
hsr.setAttribute("userName","罗西");
return "success";
}
运行测试:
三、回写数据
1.直接返回字符串
1.方式一
- 通过SpringMVC框架注入的response对象,使用response.getWriter().print("hello world”)回写数据,此时不需要视图跳转,业务方法返回值为void。
//回写数据
@RequestMapping(value = "/quick6")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().write("Hello World!");
}
运行测试:
1.方式二
- 将需要回写的字符串直接返回,但此时需要通过@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回。
@RequestMapping(value = "/quick7")
@ResponseBody //告诉SpringMVC框架不进行视图跳转,直接进行数据响应
public String save7() throws IOException {
return "hello World!";
}
运行测试:
1.方式三
先创建一个User实体类
@RequestMapping(value = "/quick8")
@ResponseBody //告诉SpringMVC框架不进行视图跳转,直接进行数据响应
public String save8() throws IOException {
return "{\"username\":\"jack\",\"age\":20}";
}
运行测试:
1.方式四
先导入依赖:
<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-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
@RequestMapping(value = "/quick9")
@ResponseBody //告诉SpringMVC框架不进行视图跳转,直接进行数据响应
public String save9() throws IOException {
User u=new User();
u.setUsername("tom");
u.setAge(45);
//使用json转换工具将对象转换为json格式字符串再返回
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(u);
return json;
}
运行测试:
2.返回对象和集合
1. 配置处理器映射器
- 通过SpringMVC帮助我们对对象或集合进行json字符串的转换并回写,为处理器适配器配置消息转换参数指定使用jackson进行对象或集合的转换,因此需要在spring-mvc.xml中进行如下配置。
<!-- 配置处理器映射器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>
@RequestMapping(value = "/quick10")
@ResponseBody //告诉SpringMVC框架不进行视图跳转,直接进行数据响应
public User save10() throws IOException {
User u=new User();
u.setUsername("world");
u.setAge(18);
return u;
}
运行测试:
2.注解
- 在方法上添加@ResponseBody就可以返回son格式的字符串,但是这样配置比较麻烦,配置的代码比较多,因此,我们可以使用mvc的注解驱动代替上述配置。
< !—-mvc的注解驱动-->
<mvc :annotation-driven/>
- 在SpringMVC的各个组件中,处理器映射器、处理器适配器、视图解析器称为SpringMVC的三大组件。使用自动加载RequestMappingHandlerMapping (处理映射器)和
RequestMappingHandlerAdapter(处理适配器),可用在Spring-xml.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。
- 同时使用默认底层就会集成jackson进行对象或集合的json格式字符串的转换.
mvc注解驱动:
<!-- mvc注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
四、详细代码
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SpringMVC-Demo1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</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-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
2.web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<!-- 配置SpringMVC前端控制器-->
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:http="http://www.springframework.org/schema/c"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--Controller的组件扫描-->
<context:component-scan base-package="com.study.controller"></context:component-scan>
<!--配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置处理器映射器-->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>-->
<!-- mvc注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
4.success.jsp
<%--
Created by IntelliJ IDEA.
User: 86166
Date: 2022/6/26
Time: 9:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Success.......${userName}</h1>
</body>
</html>
5.User
package com.study.domain;
public class User {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
}
6.UserController
package com.study.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/quick10")
@ResponseBody //告诉SpringMVC框架不进行视图跳转,直接进行数据响应
public User save10() throws IOException {
User u=new User();
u.setUsername("world");
u.setAge(18);
return u;
}
@RequestMapping(value = "/quick9")
@ResponseBody //告诉SpringMVC框架不进行视图跳转,直接进行数据响应
public String save9() throws IOException {
User u=new User();
u.setUsername("tom");
u.setAge(45);
//使用json转换工具将对象转换为json格式字符串再返回
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(u);
return json;
}
@RequestMapping(value = "/quick8")
@ResponseBody //告诉SpringMVC框架不进行视图跳转,直接进行数据响应
public String save8() throws IOException {
return "{\"username\":\"jack\",\"age\":20}";
}
@RequestMapping(value = "/quick7")
@ResponseBody //告诉SpringMVC框架不进行视图跳转,直接进行数据响应
public String save7() throws IOException {
return "hello World!";
}
//回写数据
@RequestMapping(value = "/quick6")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().write("Hello World!");
}
//不常用
@RequestMapping(value = "/quick5")
public String save5(HttpServletRequest hsr){
//设置模型数据
hsr.setAttribute("userName","罗西");
return "success";
}
@RequestMapping(value = "/quick4")
public String save4(Model model){
//设置模型数据
model.addAttribute("userName","马奎斯");
return "success";
}
@RequestMapping(value = "/quick3")
public ModelAndView save3(ModelAndView modelAndView){
//设置模型数据
modelAndView.addObject("userName","小马哥");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping(value = "/quick2")
public ModelAndView save2(){
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("userName","小飞侠");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping(value = "/quick",method = RequestMethod.GET,params = {"userName"})
public String save(){
System.out.println("UserController....");
/*return "success.jsp";*/
/*return "/jsp/success.jsp";*/
return "success";
}
}