SpringMVC2——数据响应

SpringMVC2——数据响应

SpringMVC的数据响应方式

  1. 页面跳转
    • 直接返回字符串
    • 通过ModelAndView对象返回
  2. 回写数据
    • 直接返回字符串
      1. 通过SpringMVC框架注入的response对象,使用response.getWriter().print(“hello world”)回写数据,此时不需要视图跳转,业务方法返回值为void
      2. 将需要的字符串直接返回,但此时需要通过@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回
    • 返回对象或集合
      1. 在方法上添加@ResponseBody就可以返回json格式的字符串,但是这样配置比较麻烦,配置的代码较多,因此,可以使用mvc的注解驱动代替上述的位置
      2. < mvc:annotation-driven /> mvc的注解驱动
        • 在SpeingMVC的各个组件中,处理器映射器,处理器适配器,视图解析器称为SpringMVC的三大组件
        • 使用< mvc:annotation-driven >自动加载处理器和适配器
          • RequestMappingHandlerMapping(处理器映射器)
          • RequestMappingHandlerAdapter(处理器适配器)
        • 使用< mvc:annotation-driver>默认底层就会集成jackson进行对象或集合的json格式字符串转换

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: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.itheima">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

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

<!--&lt;!&ndash;    配置处理器映射器&ndash;&gt;-->
<!--    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">-->
<!--        <property name="messageConverters">-->
<!--            <list>-->
<!--                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>-->
<!--            </list>-->
<!--        </property>-->
<!--    </bean>-->
<!--    mvc的注解驱动-->
    <mvc:annotation-driven/>
</beans>

示例的代码

package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.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",method = RequestMethod.GET)
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    //期望Spring框架自动将User转换成Json格式的字符串
    public User save10() throws IOException{
        User user = new User();
        user.setUsername("zhangsan");
        user.setAge(18);

        return user;
    }

    @RequestMapping(value="/quick9",method = RequestMethod.GET)
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    public String save9() throws IOException{
        User user = new User();
        user.setUsername("zhangsan");
        user.setAge(18);
        //使用Json的转换工具将对象
        ObjectMapper objectMapper = new ObjectMapper();

        String json = objectMapper.writeValueAsString(user);
        return json;
    }

    @RequestMapping(value="/quick8",method = RequestMethod.GET)
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    public String save8(){
        return "{\"username\":\"zhansan\",\"age\":18}";
    }

    @RequestMapping(value="/quick7",method = RequestMethod.GET)
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    public String save7(){
        return "success";
    }

    @RequestMapping(value="/quick6",method = RequestMethod.GET)
    public void save6(HttpServletResponse response){
        try {
            response.getWriter().print("<h1>hello world</h1>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value="/quick5",method = RequestMethod.GET)
    public String save5(HttpServletRequest request){
        request.setAttribute("username","鬼王");

        return "success";
    }

    @RequestMapping(value="/quick4",method = RequestMethod.GET)
    public String save4(Model model){
        model.addAttribute("username","鬼谷");
        return "success";
    }

    @RequestMapping(value="/quick3",method = RequestMethod.GET)
    public ModelAndView save3(ModelAndView view){

        view.addObject("username","itcast");
        //设置视图名字
        view.setViewName("success");

        return view;
    }


    @RequestMapping(value="/quick2",method = RequestMethod.GET)
    //@RequestMapping("/quick")
    public ModelAndView save2(){
        /*
        model 模型  作用封装数据
        View  视图  作用是展示数据
         */
        ModelAndView view = new ModelAndView();
        //设置模型数据
        view.addObject("username","itcast");
        //设置视图名字
        view.setViewName("success");
        return view;
    }


    @RequestMapping(value="/quick",method = RequestMethod.GET)
    //@RequestMapping("/quick")
    public String save(){
        System.out.println("Controller save running....");
        return "success";
    }

}

SpringMVC获得请求数据

  1. 获得请求参数
    • 客户端请求参数的格式是:name=value&name=value…
    • 服务器端要获得请求的参数,有时还需要进行数据的封装,SpringMVC可以接收如下类型的参数:
      1. 基本数据类型参数
        • Controller中的业务方法的参数名称要与请求参数的name一致,参数值会自动映射匹配
      2. POJO类型参数 : 简单javaBean类型
        • Controller中的业务方法的POJO参数的属性名与请求类型的name一致,参数值会自动映射匹配
      3. 数组类型参数
      4. 集合类型参数
        • 获得集合参数时,要将集合参数包装到一个POJO中才可以
        • 当使用ajax提交时,可以指定contentType为json形式,那么在方法参数位置使用@ResponseBody可以直接接收集合数据而无需使用POJO进行封装
  2. 请求数据的乱码问题
    • 当post请求时,数据会出现乱码,我们可以设置一个过滤器来进行编码的过滤
      在web.xml中配置一个Filter:
<!--配置全局过滤的filter-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  1. 参数绑定注解@requestParam
  • 当请求的参数名称与Controller的业务方法参数名称不一致时,就需要通过@RequestParam注解显式的绑定
  • 参数 :
    • value : 与请求参数的名称
    • required : 此在指定的请求参数是否必须包括,默认是true,提交如果没有此参数就报错
    • defaultValue : 当没有指定请求参数时,则使用指定的默认参数
    //获得基本类型参数
    @RequestMapping(value="/quick16")
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    public void save16(@RequestParam(value="name",required=false,defaultValue="") String username) throws IOException{
        System.out.println(username);
    }
  1. 获取Restful风格的参数
    • Restful是一种架构风格,设计风格,而不是标准,只是提供了一组设计原则和约束条件,主要用于客户端和服务器交互类的软件,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存机制
    • Restful风格的请求时使用"url+请求方式"表示一次请求目的的,HTTP协议里面四个表示操作方式的动词如下:
      • GET : 用于获取资源
      • POST : 用于新建资源(添加一个用户数据)
      • PUT : 用于更新资源
      • DELETE : 用于删除资源
    • 例如 :
      • /user/1 GET : 得到id=1的user
      • /user/1 DELETE : 删除id=1的user
      • /user/1 PUT : 更新id=1的user
      • /user POST : 新增user
//Restful风格的参数的获取
    //localhost:8080/user/quick/zhangsan
    @RequestMapping(value="/quick17/{username}",method = RequestMethod.POST)
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    public void save17(@PathVariable(value = "username",required = true) String username) throws IOException{
        System.out.println(username);

    }
  1. 自定义类型转换器
    • SpringMVC默认已经提供了一些常用的类型转换器,例如客户端提交的字符串转换成int型进行参数设置
    • 但是不是所有的数据类型都提供了转换器,没有提供的就需要自定义转换器,例如:日期类型的数据就需要自定义转换器
    • 自定义类型转换器类实现Converter接口
      • 定义转换器类实现Converter接口
      • 在配置文件中声明转换器,spring-mvc.xml
      • 在< annotation-driven>中引用转换器

定义的转换器类实现Converter接口:

package com.itheima.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String,Date> {
    
    @Override
    public Date convert(String s) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}

spring-mvc.xml中的配置 :

<!--    声明转换器-->
    <bean id="conversionService2" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.itheima.converter.DateConverter"/>
            </list>
        </property>
    </bean>
</beans>
  1. 获得请求头中的数据
    • @RequestHeader : 使用@RequestHeader可以获得请求头信息,相当于web阶段学习的request.getHeader(name)
      • @RequestHeader注解的属性如下 :
        • value : 请求头的名称
        • required : 是否必须携带此请求头
    • @CookieValue : 使用CookieValue可以获得指定Cookie的值
      • @CookieValue注解的属性如下 :
        • value : 指定cookie的名称
        • required : 是否必须携带此cookie
 //获取请求中Cookie的数据
    @RequestMapping(value="/quick20")
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    public void save20(@CookieValue(value = "JSESSIONID",required = false) String use) throws IOException{
        System.out.println(use);
    }

    //获取请求的数据
    @RequestMapping(value="/quick19")
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    public void save19(@RequestHeader(value = "User-Agent",required = false) String use) throws IOException{
        System.out.println(use);
    }

  1. 文件上传
  • 文件上传客户端的三要素 :
    • 表单项type = “file”
    • 表单的提交方式是post
    • 表单的enctype属性是多部份表单形式以及enctype = “multipat/form-data”
  • 文件上传原理 :
    • 当form表单修改为多部份表单时,request.getParameter()将失效
    • enctype = "application/x-www-form-urlencoded"时,form表单的正文内容格式是:
      • key=value&key=value&key=value
    • 当form表单的enctype取值为Multipart/form-data时,请求正文内容就变成多部份形式
  • 单文件上传步骤
    • 导入fileupload和io坐标
    • 配置文件上传解析器
    • 编写文件上传的代码

spring-mvc.xml中文件上传解析器的配置

<!--    配置文件上传的解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="500000"/>
    </bean>

文件上传的代码 :

//获取请求的数据
    @RequestMapping(value="/quick21")
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    public void save21(String username, MultipartFile upload) throws IOException{
        System.out.println(username);
        //获得上传文件的名称
        String originalFilename = upload.getOriginalFilename();
        upload.transferTo(new File("D:\\ATTT\\"+originalFilename));
    }
  • 多文件上传实现
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data">
    名称<input type="text" name="username"><br/>
    文件<input type="file" name="upload"><br/>
    文件2<input type="file" name="upload"><br/>
    <input type="submit" value="提交"><br/>
</form>
</body>
</html>
//多文件上传
    @RequestMapping(value="/quick23")
    @ResponseBody  //告知Spring框架,不进行视图跳转,直接进行数据返回
    public void save23(String username, MultipartFile[] upload) throws IOException{
        System.out.println(username);
        for (MultipartFile multipartFile : upload){
            String originalFilename = multipartFile.getOriginalFilename();
            multipartFile.transferTo(new File("D:\\ATTT\\"+originalFilename));
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值