【SpringMVC】:数据响应

本文详细介绍了SpringMVC中如何进行数据响应,包括通过返回字符串、ModelAndView对象、重定向和转发、使用视图控制器以及视图解析器。同时讲解了回写数据的方式,如直接返回字符串、返回对象或集合,并涉及了@RestController注解的使用。内容涵盖页面跳转的各种方法和数据响应的多种策略。
摘要由CSDN通过智能技术生成

上篇博客我们了解了请求参数的获取,那么获取到请求参数之后,需要对参数进行出来,然后进行数据响应。那么这篇博客我们就来了解 Controller 类如何进行数据响应。

1、方法返回值类型

在 web 阶段我们也了解过数据响应,我们可以简单的将数据响应分为:页面跳转和回写数据

Controller 类的业务返回的返回值类型有很多,但归根结底就是用于完成页面跳转和回写数据。我们了解一下常用的几个返回值类型:ModelAndView, Model,ModelMap,Map,View, String, void ,@ResponseBody,HttpHeaders

2、页面跳转

在 SpringMVC 中完成页面跳转有两种方式:直接返回字符串和返回 ModelAndView 对象

2.1、直接返回字符串

当直接返回一个字符串时,会自动通过视图解析器解析为物理视图地址。

@RequestMapping("/user")
public class MyController {
   //请求地址:localhost:8080/user/testReturnString
   @RequestMapping("/testReturnString")
   public String testReturnString() {
	   System.out.println("MyController 的 testReturnString 方法执行了。。。。");
	   return "success.html";
   }
}

当你的视图不是位于 user 文件夹下时,客户端会报 404 错误,因为在找不到该视图。这种方式设置是视图的相对地址,相对 MyController 类的请求地址,所以我们可以将其设置为绝对地址return "/success.html";

2.2、返回 ModelAndView 对象

ModelAndView 对象我们可以进行分解, Model 表示模型用于封装数据,View 表示视图用于展示数据。 ModelAndView 对象的一些方法:
在这里插入图片描述
使用 ModelAndView 对象完成页面跳转:

@RequestMapping("test01")
public ModelAndView test01(){
    //创建 modelAndView 对象
    ModelAndView modelAndView =new ModelAndView();
    //设置视图名称
    modelAndView.setViewName("/user.html");
    //设置模型数据
    modelAndView.addObject("user","zhangsan");
    return  modelAndView;
}

也可以不手动创建 ModelAndView 对象,直接在方法上添加形参,这种方式的ModelAndView 对象创建实参

@RequestMapping("test02")
public ModelAndView test02(ModelAndView modelAndView){
    //设置视图名称
    modelAndView.setViewName("/user.html");
    //设置模型数据
    modelAndView.addObject("user","lisi");
    return  modelAndView;
}

这两种方式是一样的,只不过 ModelAndView 对象的创建角色改变了,除了这种两种方式还有其他方式,我们可以通过ViewModel将 ModelAndView 对象拆分。

@RequestMapping("test03")
public String test03(Model model){
    model.addAttribute("user","wangwu");
    return "/user.html";
}

@RequestMapping("test04")
public String test04(ModelMap modelMap){
    modelMap.addAttribute("user","zhaoliu");
    return "/user.html";
}

2.3、重定向和转发

  1. 转发:请求转发是指将请求再转发到其他地址,转发过程中使用的是同一个请求,转发的地址栏内容不变。
  2. 重定向:是指由原请求地址重新定位到某个新地址,原有的请求失效,客户端看到的是新的请求返回的相应结果。

在SpringMVC 中默认是通过转发完成跳转的,当然也可以设置为重定向:

//转发到user.jsp
@RequestMapping("test05")
public String test05(VO vo){
    return  "forward:user.jsp";
}

//重定向user.jsp
@RequestMapping("test05")
public String test05(VO vo){
    return  "redirect:user.jsp";
}

注意:如果在方法返回值前加 forward:或者redirect: 则SpringMVC配置文件中的自定义视图解析器无效。return "forward:/main"表示转发到映射名为main的controller,而return "forward:/main.jsp"表示转发到main.jsp页面。

在方法上只有@RequestMapping 时,无论方法返回值是什么,都需要进行跳转。

2.4、使用视图控制器

当控制器方法中,仅仅用来实现页面跳转,既只需要设置视图名称时,可可以将处理器的方法使用 view-controller 标签进行表示

<mvc:view-controller path="/view" view-name="index"></mvc:view-controller>

在使用该标签时,必须在配置文件中添加<mvc:annotation-driven/>标签。

2.5、视图解析器

SpringMVC 中有一个InternalResourceViewResolver解析器,这个主要用于渲染 JSP 文件,当返回的视图没有任何前缀(forward:或者redirect:)时,InternalResourceViewResolver视图解析器会将视图名称拼接前缀和后缀形成最终路径。在 SpringMVC 的配置文件中需要对视图解析器进行配置:

<!--配置内部资源视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/"></property>
    <property name="suffix" value=".jsp"></property>
    <property name="viewNames" value="jsp*"/>
    <property name="order" value="1" />
</bean>

在 Controller 类的业务方法中就可以省略前缀和后缀,SpringMVC 将返回的字符串与在视图解析器的前后缀拼接后跳转:

@RequestMapping("test01")
public ModelAndView test01(){
    //创建 modelAndView 对象
    ModelAndView modelAndView =new ModelAndView();
    //设置视图名称
    modelAndView.setViewName("user");
    //设置模型数据
    modelAndView.addObject("user","zhangsan");
    return  modelAndView;
}

除了使用 InternalResourceViewResolver解析器,还可以引入themyleaf视图解析器,用于对 HTML 进行解析,在使用时需要引入相关坐标:

<!-- Spring5和Thymeleaf整合包 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>版本</version>
</dependency>

需要配置的文件:

<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    <!-- 视图的优先级 -->
    <property name="order" value="1"/>
    <!-- 视图的编码 -->
    <property name="characterEncoding" value="UTF-8"/>
    <!-- 返回的视图名称的规范 ,既当返回的视图名称为 th* 或者 base/ 时才能使用该视图解析器 -->
    <property name="viewNames" value="th*,base/*"/>
    <property name="templateEngine">
        <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
            <property name="templateResolver">
                <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                    <!-- 视图前缀 -->
                    <property name="prefix" value="/WEB-INF/templates/"/>
                    <!-- 视图后缀 -->
                    <property name="suffix" value=".html"/>
                    <property name="templateMode" value="HTML5"/>
                    <property name="characterEncoding" value="UTF-8" />
                </bean>
            </property>
        </bean>
    </property>
</bean>

也可以将两种视图进行整合:

 <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="viewResolvers">
        <list>
        	<!-- 这里添加视图多个视图解析器 -->
        </list>
    </property>
</bean>

3、回写数据

回写数据也有两种方式:直接返回字符串和返回对象或集合

3.1、直接返回字符串

Web基础阶段,客户端访问服务器端,如果想直接回写字符串作为响应体返回的话,只需要使用response.getWriter().print(“hello world”) 即可,所以我们通过SpringMVC框架注入的response对象,此时不需要视图跳转,业务方法返回值为void。

@RequestMapping("test05")
public void test05(HttpServletResponse response) throws IOException {
     response.getWriter().println("zhangsan");
}

除了这种方式,还有通过@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回:

@RequestMapping("test06")
@ResponseBody //告知 SpringMVC框架 不进行视图跳转,直接进行数据响应
public String test06() throws IOException {
    return "lisi";
}

在实际开发中,一般不会直接返回 “lisi” 这是类型的字符串,一般返回的是有一定格式的字符串,例如 json 格式。在返回 json 格式的字符串时,我们需要用到额外添加Jackson的jar包,在xml 文件中添加:

<!--json转换工具jackson-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.11.1</version>
</dependency>
@RequestMapping("test07")
@ResponseBody //告知 SpringMVC框架 不进行视图跳转,直接进行数据响应
public String test07() throws IOException {
    User user = new User();
    user.setAge(18);
    user.setUsername("zhangsan");
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(user);
    return  json;
}

3.2、返回对象或集合

通过 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("test08")
@ResponseBody //告知 SpringMVC框架 不进行视图跳转,直接进行数据响应
public User test08() throws IOException {
    User user = new User();
    user.setAge(18);
    user.setUsername("zhangsan");
    return  user;
}

可以使用<mvc:annotation-driven>自动加载 RequestMappingHandlerMapping(处理映射器)和RequestMappingHandlerAdapter( 处 理 适 配 器 ),可用在Spring-xml.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。

<!--mvc的注解驱动-->
<mvc:annotation-driven/>

3.3、@RestController 注解

@RestController注解是 SpringMVC 提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解

@Controller
@RequestMapping("/user")
//@RestController("/user")注解等于上述两个注解之和
public class UserController {
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值