文章目录
- 1.中文乱码处理
- 1.引出问题
- 1.恢复原来取消掉的属性绑定
- 2.启动服务器,引出问题
- 2.自定义中文乱码过滤器
- 1.MyCharacterFilter.java
- 2.web.xml配置过滤器(这个解决乱码的过滤器放到最前面)
- 3.结果展示
- 3.使用Spring过滤器处理(方便)
- web.xml
- 2.处理json和HttpMessageConverter
- 导入jar包
- 1.处理json—@ReponseBody
- 1.需求分析
- 2.具体实现
- 1.JsonHandler.java后端接口
- 2.Dog.java
- 3.json.jsp发送ajax请求
- 4.结果展示
- 2.处理json—@ResquestBody
- 1.需求分析
- 2.具体实现
- 1.User.java
- 2.JsonHandler.java(这里故意没有使用@resquestBody注解)
- 3.json2.jsp前端界面
- 4.结果展示
- 5.添加注解解决数据为空
- 6.postman测试
- 3.处理json注意事项和细节
- 1.处理json对象数组
- 1.JsonHandler.java
- 2.postman测试
- 2.将@ReponseBody直接放在类中,可以使所有的方法都生效
- 3.@ReponseBody和@Controller可以合并成一个@RestController
- 4.当使用这个@ReponseBody注解的时候会将结果转换成json字符串直接返回到发送请求的位置
- 4.HttpMessageConverter<T>
- 1.流程图
- 2.底层实现
- 3.文件下载
- 1.需求分析
- 2.具体实现
- 1.后端接口
- 2.结果展示
- 4.文件上传
- 1.基本介绍
- 2.导入jar包
- 3.具体实现
- 1.配置文件上传解析器
- 2.编写fileUpload.jsp
- 3.FileUploadHandler.java
- 4.postman测试
1.中文乱码处理
1.引出问题
1.恢复原来取消掉的属性绑定
2.启动服务器,引出问题
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() {
}
}
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>
3.结果展示
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>
2.处理json和HttpMessageConverter
导入jar包
1.处理json—@ReponseBody
1.需求分析
- 后端发送一个javabean对象给前端,可以使用注解自动将其转换成json字符串
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;
}
}
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 + '\'' +
'}';
}
}
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>
4.结果展示
2.处理json—@ResquestBody
1.需求分析
- 前端向目标方法发送一个json字符串,后端使用注解将其自动转换为javabean对象,然后再以json字符串的形式发送回去
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 + '\'' +
'}';
}
}
2.JsonHandler.java(这里故意没有使用@resquestBody注解)
@RequestMapping("/json/user")
@ResponseBody //将结果转换成json类型返回
public User getJson2(User user) {
System.out.println(user);
return user;
}
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>
4.结果展示
数据为空
5.添加注解解决数据为空
6.postman测试
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;
}
2.postman测试
2.将@ReponseBody直接放在类中,可以使所有的方法都生效
3.@ReponseBody和@Controller可以合并成一个@RestController
4.当使用这个@ReponseBody注解的时候会将结果转换成json字符串直接返回到发送请求的位置
4.HttpMessageConverter
1.流程图
2.底层实现
3.文件下载
1.需求分析
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;
}
2.结果展示
4.文件上传
1.基本介绍
2.导入jar包
3.具体实现
1.配置文件上传解析器
<!--配置文件上传解析器,注意这里的id必须是接口首字母小写-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"></bean>
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>
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";
}
}