springMVC 九、HttpMessageConverter文件上传和下载

目录

九、HttpMessageConverter

1、@RequestBody

2、RequestEntity

3、@ResponseBody

4、SpringMVC将对象转化成json

5、SpringMVC处理ajax

 6、@RestController注解(非常重要)

7、ResponseEntity(实现文件下载)

十、文件上传和下载

1、文件下载

2、文件上传


九、HttpMessageConverter

HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文

HttpMessageConverter提供了两个注解和两个类型:@RequestBody,@ResponseBody,RequestEntity,ResponseEntity

1、@RequestBody

 @RequestBody可以获取请求体,需要在控制器方法设置一个形参,使用@RequestBody进行标识,当前请求的请求体就会为当前注解所标识的形参赋值

<form th:action="@{/testRequestBody}" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="测试@RequestBody">
</form>
    @RequestMapping("/testRequestBody")
    //使用@RequestBody获取请求体
    public String testRequestBody(@RequestBody String requestBody) throws UnsupportedEncodingException {
        //输出请求体,并将url解码
        System.out.println("requestBody:"+ URLDecoder.decode(requestBody, "UTF-8"));
        return "success";
    }

输出结果:requestBody:username=张三&password=12345

2、RequestEntity

RequestEntity封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息

<form th:action="@{/testRequestEntity}" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="测试RequestEntity">
</form>
    @RequestMapping("/testRequestEntity")
    //使用RequestEntity将请求报文封装为java对象
    public String testRequestEntity(RequestEntity<String> requestEntity) throws UnsupportedEncodingException {
        //获取请求头
        System.out.println("请求头:"+requestEntity.getHeaders());
        //获取请求体
        System.out.println("请求体:"+URLDecoder.decode(requestEntity.getBody(),"UTF-8"));
        return "success";
    }

输出结果:

请求头:[host:"localhost:8080", connection:"keep-alive", content-length:"40", cache-control:"max-age=0", sec-ch-ua:"" Not A;Brand";v="99", "Chromium";v="102", "Google Chrome";v="102"", sec-ch-ua-mobile:"?0", sec-ch-ua-platform:""Windows"", upgrade-insecure-requests:"1", origin:"http://localhost:8080", user-agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36", accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", sec-fetch-site:"same-origin", sec-fetch-mode:"navigate", sec-fetch-user:"?1", sec-fetch-dest:"document", referer:"http://localhost:8080/springMVC_demo4/", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9,en-GB;q=0.8,en-US;q=0.7,en;q=0.6", cookie:"Idea-87c2ee2b=73b3225d-f813-4b7a-aec7-ff8cc48ee37e", Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]
请求体:username=张三&password=123

3、@ResponseBody

使用servletAPI的Response对象来响应浏览器数据

<a th:href="@{/testResponse}">测试servletAPI的Response对象来响应浏览器数据</a>
    @RequestMapping("/testResponse")
    public void testResponse(HttpServletResponse response) throws IOException {
        //设置编码,解决中文乱码
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print("你好! hello,response");
    }

 

@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器

响应数据中文乱码解决办法https://blog.csdn.net/qq_57389269/article/details/123798992

<a th:href="@{/testResponseBody}">测试@ResponseBody响应浏览器数据</a><br>
    @RequestMapping(value = "/testResponseBody", produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"})
    @ResponseBody
    public String testResponseBody(){
        //不加@ResponseBody,则返回的是一个视图名称,加上则就表示一个纯字符串
        return "成功";
    }

 

4、SpringMVC将对象转化成json

@ResponseBody处理json的步骤:

a>导入jackson的依赖

<!--        json数据处理-->
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.3</version>
        </dependency>

 b>在SpringMVC的核心配置文件中开启mvc的注解驱动,此时在HandlerAdaptor中会自动装配一个消息转换器:MappingJackson2HttpMessageConverter,可以将响应到浏览器的Java对象转换为Json格式的字符串

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

c>在控制器方法上使用@ResponseBody注解进行标识

d>将Java对象直接作为控制器方法的返回值返回,就会自动转换为Json格式的字符串

实体类:

public class User {

    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String sex;

    public User() {
    }

    public User(Integer id, String username, String password, Integer age, String sex) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
        this.sex = sex;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

控制器方法:

    @RequestMapping(value = "/testResponseUser")
    @ResponseBody
    public User testResponseUser(){
        return new User(1001,"张三","12345",22,"男");
    }

链接:

<a th:href="@{/testResponseUser}">测试@ResponseBody响应浏览器User对象</a><br>

5、SpringMVC处理ajax

a>请求超链接:

<div id="app">
    <a th:href="@{/testAxios}" @click="testAxios">SpringMVC处理ajax</a><br>
</div>

b>通过vue和axios处理点击事件:

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
<script type="text/javascript">
    new Vue({
        el:"#app",
        methods:{
            testAxios:function (event) {
                axios({
                    method:"post",
                    url:event.target.href,
                    param:{
                        username:"张三",
                        password:"12345"
                    }
                }).then(function (response) {
                    alert(response.data);
                });
                event.preventDefault();
            }
        }
    });
</script>

在SpringMVC.xml文件配置 

    <!--    开放对静态资源的访问-->
    <mvc:default-servlet-handler/>
<!--    开启注解驱动-->
    <mvc:annotation-driven/>

c>控制器方法:

    @RequestMapping("/testAxios")
    @ResponseBody
    public String testAxios(String username, String password){
        System.out.println(username + ',' + password);
        return "hello,axios";
    }

结果:

 提示:在axios中已经阻止页面跳转,执行弹框,如果还是跳转,重新执行maven打包

 6、@RestController注解(非常重要)

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

7、ResponseEntity(实现文件下载)

ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文

十、文件上传和下载

1、文件下载

使用ResponseEntity实现下载文件的功能

<a th:href="@{/testDown}">下载测试</a>
 @RequestMapping("/testDown")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/static/img/mm景色.jpeg");
        //创建输入流
        InputStream is = new FileInputStream(realPath);
        //创建字节数组
        byte[] bytes = new byte[is.available()];
        //将流读到字节数组中
        is.read(bytes);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment;filename=mm景色.jpeg");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
        //关闭输入流
        is.close();
        return responseEntity;
    }

 另一种方式参考文件下载https://blog.csdn.net/m0_62520968/article/details/124900717?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165503555116780357235899%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=165503555116780357235899&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-124900717-null-null.nonecase&utm_term=%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD&spm=1018.2226.3001.4450

2、文件上传

文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data"

SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息

上传步骤:

<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
    头像:<input type="file" name="photo"><br>
    <input type="submit" value="上传">
</form>

a>添加依赖:

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

b>在SpringMVC的配置文件中添加配置:

<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

c>控制器方法:

    @RequestMapping("/testUp")
    public String testUp(MultipartFile photo, HttpSession session) throws IOException {
        //获取上传的文件的文件名
        String fileName = photo.getOriginalFilename();
        //处理文件重名问题
        String hzName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + hzName;
        //获取服务器中photo目录的路径
        ServletContext servletContext = session.getServletContext();
        String photoPath = servletContext.getRealPath("photo");
        File file = new File(photoPath);
        if(!file.exists()){
            file.mkdir();
        }
        String finalPath = photoPath + File.separator + fileName;
        //实现上传功能
        photo.transferTo(new File(finalPath));
        return "success";
    }

上传到target的SNAPSHOT

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值