此部分内容将包含 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 等)的更多相关文章

  1. C++ 之Boost 实用工具类及简单使用

    本文将介绍几个 Boost 实用工具类,包括 tuple.static_assert.pool.random 和 program_options等等.需要对标准 STL 具备一定的了解才能充分理解本文 ...

  2. 实用篇:说说我在JavaScript项目中使用的工具类

    在JavaScript的开发中,我们都会写一些工具类来帮我们简化一些业务操作的逻辑,一下就貼几个我在项目开发过程中常用的工具类.表达能力有限,各位看官还是看源码吧. 一.日期处理工具类. /** * ...

  3. 重复造轮子,编写一个轻量级的异步写日志的实用工具类(LogAsyncWriter)

    一说到写日志,大家可能推荐一堆的开源日志框架,如:Log4Net.NLog,这些日志框架确实也不错,比较强大也比较灵活,但也正因为又强大又灵活,导致我们使用他们时需要引用一些DLL,同时还要学习各种用 ...

  4. Java日期时间实用工具类

    Java日期时间实用工具类 1.Date (java.util.Date)    Date();        以当前时间构造一个Date对象    Date(long);        构造函数   ...

  5. Java语言Lang包下常用的工具类介绍_java - JAVA

    文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 无论你在开发哪中 Java 应用程序,都免不了要写很多工具类/工具函数.你可知道,有很多现成的工具类可用,并且代码质量都 ...

  6. JAVA中封装JSONUtils工具类及使用

    在JAVA中用json-lib-2.3-jdk15.jar包中提供了JSONObject和JSONArray基类,用于JSON的序列化和反序列化的操作.但是我们更习惯将其进一步封装,达到更好的重用. ...

  7. java Http消息传递之POST和GET两种方法--通过实用工具类来获取服务器资源

    实现该方法需要导入一些jar包 可以去一下地址下载: http://pan.baidu.com/s/1hqrJF7m /** * 实用工具类来获取服务器资源 * * get方法传送数据 * * 1.通 ...

  8. commons-lang3-3.2.jar中的常用工具类的使用

    这个包中的很多工具类可以简化我们的操作,在这里简单的研究其中的几个工具类的使用. 1.StringUtils工具类 可以判断是否是空串,是否为null,默认值设置等操作: /** * StringUt ...

  9. Android 中替代 sharedpreferences 工具类的实现

    Android 中替代 sharedpreferences 工具类的实现 背景 想必大家一定用过 sharedpreferences 吧!就我个人而言,特别讨厌每次 put 完数据还要 commit. ...

随机推荐

  1. springboot2.1.3集成单节点elasticsearch6.4.0

    本案例写了一个关于医生医院搜索的例子,包括求和模式下的打分(分值与相关性有关)搜索,单节点时切勿配置节点名称和节点ip.github地址:https://github.com/zhzhair/spri ...

  2. 使用SpringSecurity体验OAuth2 (入门2)

    本文继续使用SpringSecurity从实战角度对OAuth2进行体验,上一篇 搭建了项目环境,并对配置做了初步分析,分析发现会有两套配置可能在影响OAuth,一个是由授权服务的启动类上的注解@En ...

  3. 使用scrapy爬虫,爬取今日头条搜索吉林疫苗新闻(scrapy+selenium+PhantomJS)

    这一阵子吉林疫苗案,备受大家关注,索性使用爬虫来爬取今日头条搜索吉林疫苗的新闻 依然使用三件套(scrapy+selenium+PhantomJS)来爬取新闻 以下是搜索页面,得到吉林疫苗的搜索信息, ...

  4. 看我如何粘贴别人代码--socketserver

    源码执行流程 自己模仿一个(提取代码) 服务器类 import socket import threading import selectors class TCPServer: def __init ...

  5. 【easy】530. Minimum Absolute Difference in BST

    找BST树中节点之间的最小差值. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode ...

  6. 关于typecho0.9代码高亮与数学公式支持

    闲来无事,搭了一个博客,记录一下自己的学习生活,博客模板取自原来typecho官方博客,稍加修改,改了一下涂装,不得不说插件支持有一些问题,目前大多数插件已经同步更新到typecho1.0版本,新插件 ...

  7. HTTP协议详解(四)

    接着第三篇继续学习.... 9 Cookie和Session的比较 Cookie和Session都为了用来保存状态信息,都是保存客户端状态的机制,它们都是为了解决HTTP无状态的问题而所做的努力. S ...

  8. java类(Class)的概念;对象的概念,声明类的属性 和方法,局部变量和成员变量,面向对象编程思维,抽象的概念

    类(Class)的概念 类是对一组具有相同特征和行为的对象的抽象描述. 理解: [1] 类包含了两个要素:特性和行为 => 同一类事物具有相同的特征和行为. [2] 类是一个群体性概念.例如:网 ...

  9. 解决百度上传WebUploader在IE浏览器下点击无反应的问题

    原因1:IE浏览器不支持H5方式上传,需要使用flash的方式上传 解决方法:在页面head标签添加<meta http-equiv="X-UA-Compatible" co ...

  10. UNIX哲理名言(中英文对照)

    UNIX 的特点: Everything (including hardware) is a file.所有的事物(甚至硬件本身)都是一个的文件. Configuration data stored ...