赞
踩
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() { } }
<!--配置过滤器——放到最前面,因为这个应该是最先处理的-->
<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>
<!--配置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>
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; } }
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 + '\'' + '}'; } }
<%-- 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>
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 + '\'' + '}'; } }
@RequestMapping("/json/user")
@ResponseBody //将结果转换成json类型返回
public User getJson2(User user) {
System.out.println(user);
return user;
}
<%-- 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>
数据为空
//编写方法,以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;
}
//编写方法,响应用户下载文件的需求 @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; }
<!--配置文件上传解析器,注意这里的id必须是接口首字母小写-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"></bean>
<%-- 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>
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"; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。