注:学习笔记,比较杂乱。
响应json数据
<script> $(function () { $("#btn").click(function () { $.ajax({ //编写json格式,设置属性和值 url: "/user/testAjax2", contentType: "application/json;charset=UTF-8", data: '{"username":"王五","password":"123456","age":30}', dataType: "json", type: "post", success: function (data) { //服务器端响应的数据 alert(data); alert(data.username); alert(data.password); alert(data.age); } }); }); }); </script>
@Controller @RequestMapping("/user") public class UserController { /** * 模拟异步请求响应 */ @RequestMapping("/testAjax2") @ResponseBody public User testAjax2(@RequestBody User user) { System.out.println("执行了……"); //客户端发送ajax请求,传的是json字符串,后台把json字符串封装到user对象中了 System.out.println(user); //做响应,模拟查询数据库 user.setUsername("宋庆国"); user.setAge(40); //作响应 return user; } }
jar包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.11.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.11.0</version> </dependency>
文件上传
文件上传必要条件
- form表单的enctype取值必须是:multipart/form-data(默认值是:application/x-www-form-urlencoded)。enctype是表单请求正文的类型。
- method属性必须是Post
- 提供一个文件选择域<input type="file">
- 文件选择域的name属性与文件上传方法(testUpFile)的参数名严格一致
- 配置文件解析器,id必须为"multipartResolver"代码如下:
<!--配置文件解析器,要求id必须为"multipartResolver"!!!!!!--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485706"/> </bean>
<form enctype="multipart/form-data" method="post" action="/upFile/testUpFile"> 选择文件: <input type="file" name="upload"> <button type="submit">上传</button> </form>
@RequestMapping("/testUpFile") public String testUpFile(HttpServletRequest request, MultipartFile upload) throws Exception { String path = request.getSession().getServletContext().getRealPath("/uploads/"); System.out.println(path); File file = new File(path); if (!file.exists()) { file.mkdirs(); } String filename = upload.getOriginalFilename(); String uuid= UUID.randomUUID().toString().replace("-",""); upload.transferTo(new File(path,filename)); return "success"; }
SpringMVC文件上传原理
跨服务器上传
实际开发中,我们会遇到很多处理不同功能的服务器(这里说的不是服务器集群),例如:
应用服务器:负责部署我们的应用
数据库服务器:运行我们的数据库
缓存和消息服务器:负责处理大并发访问的缓存和消息
文件服务器:负责存储用户上传文件的服务器
用到的jar包:
(未完无续)