当前位置:   article > 正文

SpringMVC进阶(过滤器解决中文乱码,处理json以及文件上传下载)

SpringMVC进阶(过滤器解决中文乱码,处理json以及文件上传下载)

1.中文乱码处理

1.引出问题
1.恢复原来取消掉的属性绑定

image-20240229123707680

image-20240229123653032

2.启动服务器,引出问题

image-20240229123751063

image-20240229123805927

2.自定义中文乱码过滤器
1.MyCharacterFilter.java
package com.sun.web.filter;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author 孙显圣
 * @version 1.0
 */
public class MyCharacterFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //在这里解决中文乱码问题
        servletRequest.setCharacterEncoding("utf-8");
        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
2.web.xml配置过滤器(这个解决乱码的过滤器放到最前面)
    <!--配置过滤器——放到最前面,因为这个应该是最先处理的-->
    <filter>
        <filter-name>MyCharacterFilter</filter-name>
        <filter-class>com.sun.web.filter.MyCharacterFilter</filter-class>
    </filter>
    <!--过滤所有请求-->
    <filter-mapping>
        <filter-name>MyCharacterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
3.结果展示

image-20240229125104279

image-20240229125119424

3.使用Spring过滤器处理(方便)
web.xml
    <!--配置Spring自带的过滤器,解决乱码问题-->
    <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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

2.处理json和HttpMessageConverter

导入jar包

image-20240229131153116

1.处理json—@ReponseBody
1.需求分析
  • 后端发送一个javabean对象给前端,可以使用注解自动将其转换成json字符串

image-20240229131232344

image-20240229131241134

2.具体实现
1.JsonHandler.java后端接口
package com.sun.web.json;

import com.sun.web.json.entity.Dog;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 孙显圣
 * @version 1.0
 */
//作为Controller注入容器
@Controller
public class JsonHandler {
    @RequestMapping("/json/dog")
    @ResponseBody //将结果转换成json类型返回
    public Dog getJson() {
        Dog dog = new Dog("小狗", "北京四合院");
        return dog;
    }
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
2.Dog.java
package com.sun.web.json.entity;

/**
 * @author 孙显圣
 * @version 1.0
 */
public class Dog {
    private String name;
    private String address;

    public Dog() {
    }

    public Dog(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
3.json.jsp发送ajax请求
<%--
  Date: 2024/2/29
  Time: 13:23
  User: 孙显圣
  Version:1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="script/jquery-3.6.0.min.js"></script>
    <script>
        $(function () {
            //绑定点击事件
            $("#getJson").click(function (){
                let url = this.href;
                let args = {"time": new Date}; //发送一个时间,防止页面缓存
                //发送ajax请求
                $.post(
                    url,
                    args,
                    function (data) {
                        console.log("dog.name=", data.name);
                        console.log("dog.address=", data.address);
                    },
                    "json"
                )
                //阻止超链接提交
                return false;
            })
        })
    </script>
</head>
<body>
<a href="json/dog" id="getJson">点击获取json数据</a>
</body>
</html>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
4.结果展示

image-20240229140024390

2.处理json—@ResquestBody
1.需求分析
  • 前端向目标方法发送一个json字符串,后端使用注解将其自动转换为javabean对象,然后再以json字符串的形式发送回去

image-20240229140739133

2.具体实现
1.User.java
package com.sun.web.json.entity;

/**
 * @author 孙显圣
 * @version 1.0
 */
public class User {
    private String userName;
    private String age;

    public User() {
    }

    public User(String userName, String age) {
        this.userName = userName;
        this.age = age;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
2.JsonHandler.java(这里故意没有使用@resquestBody注解)
    @RequestMapping("/json/user")
    @ResponseBody //将结果转换成json类型返回
    public User getJson2(User user) {
        System.out.println(user);
        return user;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
3.json2.jsp前端界面
<%--
  Date: 2024/2/29
  Time: 14:13
  User: 孙显圣
  Version:1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="script/jquery-3.6.0.min.js"></script>
    <script>
        $(function () {
            //绑定添加用户按钮
            $("button[name='butt1']").click(function () {
                //得到用户输入信息
                var userName = $("#userName").val();
                var age = $("#age").val();
                //封装成json对象
                var jsonObject = {"userName": userName, "age": age};
                //转换成json字符串
                var jsonString = JSON.stringify(jsonObject);
                //编写url
                var url = "/springmvc/json/user";
                //编写contentType,来告诉后端发送数据类型是json
                var contentType = "application/json;charset=utf-8";
                //发送ajax请求
                $.ajax({
                    url: url,
                    data: jsonString,
                    type: "post",
                    success: function (data) {
                        console.log("返回的数据是=", data);
                    },
                    contentType: contentType,
                    dataType: "json"
                })
            })
        })
    </script>
</head>
<body>
u:<input type="text" id="userName"><br>
a:<input type="text" id="age"><br>
<button name="butt1">添加用户</button>
</body>
</html>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
4.结果展示

数据为空

image-20240229144737390

image-20240229144854613

5.添加注解解决数据为空

image-20240229145947253

6.postman测试

image-20240229150328348

3.处理json注意事项和细节
1.处理json对象数组
1.JsonHandler.java
    //编写方法,以json格式返回多个dog
    @RequestMapping("/json/dogs")
    @ResponseBody //将结果转换成json类型返回
    public List<Dog> getJson3(@RequestBody List<Dog> dogs) { //接受请求的json对象数组字符串,并自动封装到dogs中
        for (Dog dog : dogs) {
            System.out.println(dog);
        }
        return dogs;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
2.postman测试

image-20240229151740727

2.将@ReponseBody直接放在类中,可以使所有的方法都生效
3.@ReponseBody和@Controller可以合并成一个@RestController
4.当使用这个@ReponseBody注解的时候会将结果转换成json字符串直接返回到发送请求的位置
4.HttpMessageConverter
1.流程图

image-20240229153352503

2.底层实现

image-20240229153505308

3.文件下载

1.需求分析

image-20240229160330675

2.具体实现
1.后端接口
    //编写方法,响应用户下载文件的需求
    @RequestMapping("/downFile")
    public ResponseEntity<byte[]> downFile(HttpSession session) throws Exception {
        //构建这个对象并返回
        //public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status)

        //@Nullable T body
        //1.获取要下载的本地文件的流
        InputStream resourceAsStream = session.getServletContext().getResourceAsStream("/img/7.png");
        //2.创建一个byte数组来接收
        byte[] bytes = new byte[resourceAsStream.available()];
        //3.使用输入流读取信息到数组中
        resourceAsStream.read(bytes);

        //HttpStatus status
        //4.获取一个状态码
        HttpStatus ok = HttpStatus.OK;

        //@Nullable MultiValueMap<String, String> headers
        //5.构建一个响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        //attachment表示以附件的形式,filename是指下载后的
        httpHeaders.add("Content-Disposition", "attachment;filename=2.jpg");

        //构建这个ResponseEntity<byte[]>
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, ok);
        return responseEntity;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
2.结果展示

image-20240229165107469

4.文件上传

1.基本介绍

image-20240229165327168

2.导入jar包

image-20240229165549493

3.具体实现
1.配置文件上传解析器
    <!--配置文件上传解析器,注意这里的id必须是接口首字母小写-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"></bean>
  • 1
  • 2
2.编写fileUpload.jsp
<%--
  Date: 2024/2/29
  Time: 16:59
  User: 孙显圣
  Version:1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
  文件介绍:<input type="text" name="introduce"><br>
  选择文件:<input type="file" name="file"><br>
  <input type="submit" value="上传文件">
</form>

</body>
</html>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
3.FileUploadHandler.java
package com.sun.web.fileupload;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Controller
public class FileUploadHandler {

    @RequestMapping("/upload")
    public String fileUpload(MultipartFile file, HttpServletRequest request, String introduce) throws IOException {
        System.out.println("文件的描述为:" + introduce);
        //接受要提交的文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println("文件名:" + originalFilename);
        //找到要上传的文件路径
        String realPath = request.getServletContext().getRealPath("/img/");
        String toSavePath = realPath + originalFilename;
        File file1 = new File(toSavePath);
        //将文件转存
        //创建一个文件对象
        file.transferTo(file1);
        return "success";
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
4.postman测试

image-20240229190400664

image-20240229190510781

image-20240229190519708

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/527158
推荐阅读
相关标签
  

闽ICP备14008679号