- 一、RESTful
- 1、RESTful的实现
- 2、HiddenHttpMethodFilter
- 3、 web.xml两个过滤器的优先级
- 二、HttpMessageConverter
- 1、@RequestBody
- 2、RequestEntity
- 3、@ResponseBody
- 4、SpringMVC处理json
- 5、SpringMVC处理ajax
- 6、 @RestController注解
- 7、ResponseEntity
- 三、文件的下载与上传
- 1、文件下载
- 2、文件上传
具体说,就是 HTTP 协议里面,四个表示 *** 作方式的动词:GET、POST、PUT、DELETE。
它们分别对应四种基本 *** 作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源。
REST 风格提倡 URL 地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为 URL 地址的一部分,以保证整体风格的一致性。
*** 作 | 传统方式 | REST风格 |
---|---|---|
查询 *** 作 | getUserById?id=1 | user/1–>get请求方式 |
保存 *** 作 | saveUser | user–>post请求方式 |
删除 *** 作 | deleteUser?id=1 | user/1–>delete请求方式 |
更新 *** 作 | updateUser | user–>put请求方式 |
例子如下:
test_rest.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a th:href="@{/user}">查询所有的用户信息</a><br>
<a th:href="@{/user/1}">根据Id查询用户信息</a><br>
<form th:action="@{/user}" method="post">
用户名:<input type="text" name="username"><br>
密码<input type="password" name="password"><br>
<input type="submit" value="add"><br>
</form>
</body>
</html>
效果图:
controller
@Controller
public class UserController {
/**
* 使用RESTFul模拟实现用户资源的增删改查
* /user GET 查询所有的用户信息
* /user/1 GET 根据用户id查询用户信息
* /user POST 添加用户信息
* /user/1 DELETE 通过主键删除用户信息
* /user PUT 修改用户信息
*/
@RequestMapping(value = "/user",method = RequestMethod.GET)
public String getAllUser(){
System.out.println("查询所有的用户信息");
return "success";
}
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
public String getUserById(){
System.out.println("根据ID查询用户信息");
return "success";
}
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String insertUser(String username,String password){
System.out.println("添加用户信息"+ username+","+password);
return "success";
}
}
控制台的输出情况:
web.xml文件需要进行配置:
<!--配置HiddenHttpMethodFilter-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern> /*
现在附上web.xml当前完整的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置HiddenHttpMethodFilter-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceResponseEncoding
true
CharacterEncodingFilter
/*
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springMVC.xml
1
DispatcherServlet
/
由于浏览器只支持发送get和post方式的请求,那么该如何发送put和delete请求呢?
SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们将 POST 请求转换为 DELETE 或 PUT 请求
HiddenHttpMethodFilter 处理put和delete请求的条件:
a>当前请求的请求方式必须为post
b>当前请求必须传输请求参数_method
满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求的请求方式转换为请求参数_method的值,因此请求参数_method的值才是最终的请求方式
首先:如果在前端界面中,直接写成PUT方法,那么会默认使用,GET方法,没有办法识别put方法,所以此时需要对web.xml进行配置HiddenHttpMethodFilter,并且设置name=“_method” value=“PUT”。即可实现,那么PUT方法的实现如下:
test_rest.html
<form th:action="@{/user}" method="post" >
<input type="hidden" name="_method" value="PUT">
用户名:<input type="text" name="username"><br>
密码<input type="password" name="password"><br>
<input type="submit" value="修改"><br>
</form>
效果图:
controller
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String updateUser(String username,String password){
System.out.println("修改用户信息"+ username+","+password);
return "success";
}
控制台的输出如下:
先配置编码,后配置http,以下为web.xml文件的具体内容:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置编码过滤器-->
<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>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*
HiddenHttpMethodFilter
org.springframework.web.filter.HiddenHttpMethodFilter
HiddenHttpMethodFilter
/*
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springMVC.xml
1
DispatcherServlet
/
二、HttpMessageConverter
HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文
HttpMessageConverter提供了两个注解和两个类型:@RequestBody,@ResponseBody,RequestEntity,
ResponseEntity
1、@RequestBody@RequestBody可以获取请求体,需要在控制器方法设置一个形参,使用@RequestBody进行标识,当前请求的请求体就会为当前注解所标识的形参赋值
index.html
<form th:action="@{testRequestBody}" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" name="测试testRequestBody注解">
</form>
controller
@Controller
public class HttpController {
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){
System.out.println("requestBody:"+requestBody);
return "success";
}
效果图:
RequestEntity封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,当前请求的请求报文就会赋值给该形参,可以通过getHeaders()获取请求头信息,通过getBody()获取请求体信息
index.html
<form th:action="@{testRequestEntity}" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" name="测试testRequestEntity">
</form>
controller
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){
//当前requestEntity表示的是整个请求的报文信息
System.out.println("请求头"+requestEntity.getHeaders());
System.out.println("请求体"+requestEntity.getBody());
return "success";
}
效果图:
@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器
index.html
<a th:href="@{/testResponseBody}">通过@ResponseBody响应游览器数据</a>
控制器
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
return "nfwlrzzwqs";
}
此时添加了@ResponseBody的注解,那就返回值就直接作为响应报文的响应体,放到浏览器
效果图如下所示:
如果此时去掉了@ResponseBody的注解,那么返回值将被视图解析器进行解析,跳转也页面,
效果如下:
controller
@RequestMapping("/testResponseBody")
public String testResponseBody(){
return "success";
}
效果图:
此时跳转的是,事先已经写好的html页面。
(现在的目的是为了返回一个对象)
@ResponseBody处理json的步骤:
在pom.xml文件中引入依赖:
<!--导入jackson的依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
b>在SpringMVC的核心配置文件中开启mvc的注解驱动,此时在HandlerAdaptor中会自动装配一个消息转换器:MappingJackson2HttpMessageConverter,可以将响应到浏览器的Java对象转换为Json格式的字符串
<mvc:annotation-driven />
c>在处理器方法上使用@ResponseBody注解进行标识
d>将Java对象直接作为控制器方法的返回值返回,就会自动转换为Json格式的字符串;
效果如下所示:
index.xml
<a th:href="@{/testResponseUser}">通过@ResponseBody响应游览器User对象</a>
控制器
@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
return new User(1001,"123456","admin",23,"男");
}
user:是自己创建的一个User类;
效果图:
(学完vue回头看)
6、 @RestController注解@RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解
7、ResponseEntityResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文
三、文件的下载与上传 1、文件下载使用ResponseEntity实现下载文件的功能
file.html
<a th:href="@{/testDown}">下载1.jpg</a>
controller:
package com.huweiqi.Controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@Controller
public class FileUpAndDownController {
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/img/1.jpg");
//创建输入流
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=1.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
}
下载的图片的放置位置:
效果图
文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
上传步骤:
a>添加依赖pom.xml:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
b>在SpringMVC的配置文件中添加配置:
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
c>(1)先对文件进行测试:
file.html
<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
头像:<input type="file" name="photo"><br>
<input type="submit" name="上传">
</form>
controller
@RequestMapping("/testUp")
public String testUp(MultipartFile photo){
System.out.println(photo.getName());
System.out.println(photo.getOriginalFilename());
return "success";
}
控制台输出:
(2)实现文件的上传
controller
@RequestMapping("/testUp")
public String testUp(MultipartFile photo,HttpSession session){
String originalFilename = photo.getOriginalFilename();
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
//判断photoPath所在的路径是否存在
if (!file.exists()){
file.mkdir();
}
String finalPath=photoPath+file.separator+originalFilename;
try {
photo.transferTo(new File(finalPath));
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
实现的效果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)