SpringMvc 中的实用工具类介绍(包括 ResponseEntity、 RestTemplate、WebUtils 等)
此部分内容将包含 ResponseEntity、 RestTemplate、WebUtils 等
1. ResponseEntity
① Sprring Mvc 中作为方法的返回值使用法
@RequestMapping("/demo")
public ResponseEntity<?> getDemo(String username) {
User user = userService.getUserByUsername(username);
if (user != null)) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.badRequest().body(null);
}
}
② 设置 header 与 多个 headers
@RequestMapping("/demo")
public ResponseEntity<?> getDemo(String username) {
User user = userService.getUserByUsername(username);
if (user != null)) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.notFound().header("MyResponseHeader", "MyValue").build("Could't found by the username");
}
}
③ 文件下载
@ResponseBody
@RequestMapping(value = "/file_download", method = RequestMethod.GET)
public ResponseEntity courseFileDownload(String name, String path) {
try {
String url = internalStorage + "/" + COURSE_MATERIAL_FILE_BUCKET + "/" + path;
InputStream inputStream = new URL(url).openStream(); InputStreamResource resource = new InputStreamResource(inputStream);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).header(HttpHeaders.CONTENT_DISPOSITION,
"attachment;filename=" + URLEncoder.encode(name, "UTF-8")).body(resource);
} catch (IOException e) {
return ResponseEntity.badRequest().body("文件不存在!");
}
}
④ 在 RestTemplate 中作为 getForEntity() 与 exchange()返回值被使用
ResponseEntity<String> entity = template.getForEntity("http://example.com", String.class);
String body = entity.getBody();
MediaType contentType = entity.getHeaders().getContentType();
HttpStatus statusCode = entity.getStatusCode();
⑤ 可以很方便地返回不同类型的结果
@RequestMapping(value = "/get_wx_acode", method = RequestMethod.GET)
public ResponseEntity getWxACode(WxACodeRequest wxACodeRequest) {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
messageConverters.add(new MappingJackson2HttpMessageConverter());
messageConverters.add(new ByteArrayHttpMessageConverter());
RestTemplate restTemplate = new RestTemplate(messageConverters);
String accessToken = fetchToken();
String aCodeUrl = String.format(
"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", accessToken);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<WxACodeRequest> entity = new HttpEntity<>(wxACodeRequest, headers);
try {
return restTemplate.postForEntity(aCodeUrl, entity, byte[].class);
} catch (RestClientException e) {
logger.error("get_wx_acode api error", e);
// or return ResponseEntity.badRequest().build(); // build for no body
return ResponseEntity.badRequest().body(ResponseResult.badRequest("400", "api error"));
}
}
2.判断字符串是否为空
StringUtils .hasText(str) 与 StringUtils .hasLength(str) 前者包含后者,并且判断不为 null,有长度,并且不全为空白字符。
3.操作 cookie 与 session
获取 cookie
@CookieValue(value="myCookie", defaultValue="someValue",required=false)
设置 cookie (还可以直接在 response header 里添加)
Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL cookie.setMaxAge(expiryTime); cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories response.addCookie(cookie);
显示声明存入 session 中的对象
public String handle(@SessionAttribute User user) {
设置 RedirectAttributes 添加 FlashAttribute
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session,
final RedirectAttributes redirectAttributes) {
if (!verify(username, password)) {
redirectAttributes.addFlashAttribute("message", "username/password invalid");
return "redirect:/login";
}
session.setAttribute(SESSION_LOGGED_IN, true);
redirectAttributes.addFlashAttribute("message", "Login Success");
return "redirect:/";
}
4.WebUtils 与 ServletRequestUtils
① 操作 参数
String param
= ServletRequestUtils.getStringParameter(
request, "param", "DEFAULT");
② 操作 session 或 cookie
WebUtils.setSessionAttribute(request, "parameter", param);
model.addAttribute("parameter", "You set: " + (String) WebUtils
.getSessionAttribute(request, "parameter"));
参考资料
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html
https://www.baeldung.com/spring-webutils-servletrequestutils
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/util/WebUtils.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html
SpringMvc 中的实用工具类介绍(包括 ResponseEntity、 RestTemplate、WebUtils 等)的更多相关文章
- C++ 之Boost 实用工具类及简单使用
本文将介绍几个 Boost 实用工具类,包括 tuple.static_assert.pool.random 和 program_options等等.需要对标准 STL 具备一定的了解才能充分理解本文 ...
- 实用篇:说说我在JavaScript项目中使用的工具类
在JavaScript的开发中,我们都会写一些工具类来帮我们简化一些业务操作的逻辑,一下就貼几个我在项目开发过程中常用的工具类.表达能力有限,各位看官还是看源码吧. 一.日期处理工具类. /** * ...
- 重复造轮子,编写一个轻量级的异步写日志的实用工具类(LogAsyncWriter)
一说到写日志,大家可能推荐一堆的开源日志框架,如:Log4Net.NLog,这些日志框架确实也不错,比较强大也比较灵活,但也正因为又强大又灵活,导致我们使用他们时需要引用一些DLL,同时还要学习各种用 ...
- Java日期时间实用工具类
Java日期时间实用工具类 1.Date (java.util.Date) Date(); 以当前时间构造一个Date对象 Date(long); 构造函数 ...
- Java语言Lang包下常用的工具类介绍_java - JAVA
文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 无论你在开发哪中 Java 应用程序,都免不了要写很多工具类/工具函数.你可知道,有很多现成的工具类可用,并且代码质量都 ...
- JAVA中封装JSONUtils工具类及使用
在JAVA中用json-lib-2.3-jdk15.jar包中提供了JSONObject和JSONArray基类,用于JSON的序列化和反序列化的操作.但是我们更习惯将其进一步封装,达到更好的重用. ...
- java Http消息传递之POST和GET两种方法--通过实用工具类来获取服务器资源
实现该方法需要导入一些jar包 可以去一下地址下载: http://pan.baidu.com/s/1hqrJF7m /** * 实用工具类来获取服务器资源 * * get方法传送数据 * * 1.通 ...
- commons-lang3-3.2.jar中的常用工具类的使用
这个包中的很多工具类可以简化我们的操作,在这里简单的研究其中的几个工具类的使用. 1.StringUtils工具类 可以判断是否是空串,是否为null,默认值设置等操作: /** * StringUt ...
- Android 中替代 sharedpreferences 工具类的实现
Android 中替代 sharedpreferences 工具类的实现 背景 想必大家一定用过 sharedpreferences 吧!就我个人而言,特别讨厌每次 put 完数据还要 commit. ...
随机推荐
- php跨域问题记录
记录跨域问题 一.问题 在控制层加了如下代码: header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN'] ); header('Ac ...
- [Kubernetes]浅谈容器网络
Veth Pair 这部分内容主要介绍一个设备: Veth Pair . 作为一个容器,它可以声明直接使用宿主机的网络栈,即:不开启 Network Namespace .在这种情况下,这个容器启动后 ...
- Acitivity(活动)
1.首先活动是放在返回栈中. 2.活动的生命周期
- 项目Alpha冲刺(团队)-第五天冲刺
格式描述 课程名称:软件工程1916|W(福州大学) 作业要求:项目Alpha冲刺(团队)-代码规范.冲刺任务与计划 团队名称:为了交项目干杯 作业目标:描述第五天冲刺的项目进展.问题困难.心得体会 ...
- 2019 icpc南昌全国邀请赛-网络选拔赛J题 树链剖分+离线询问
链接:https://nanti.jisuanke.com/t/38229 题意: 给一棵树,多次查询,每次查询两点之间权值<=k的边个数 题解: 离线询问,树链剖分后bit维护有贡献的位置即可 ...
- python基础--numpy.random
# *_*coding:utf-8 *_* # athor:auto import numpy.random #rand(d0, d1, ..., dn)n维随机值 data0 = numpy.ran ...
- django中常用的数据查询方法
https://blog.csdn.net/chen1042246612/article/details/84071006
- 关于mvc中传递匿名对象,view中无法解析
最近做项目用到MVC,发现用linq查询得到的数据是匿名类型对象,通过模型绑定.或者ViewBag.ViewData进行数据传递后,View解析报错:“object 未包含xx的定义”: 没找到好的解 ...
- js object数据类型
1.object数据类型,[可以]认为JavaScript中顶级数据类型.在JavaScript绝大多数 高级类型对象都是object类型 2.如何创建一个object类型对象 1) 通过调用Obje ...
- Initialize the shader 初始化着色器
目录 Loads the shader files and makes it usable to DirectX and the GPU 加载着色器文件并使其可用于DirectX和GPU Compil ...