此部分内容将包含 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. MailKit系列之转发电子邮件

    原文:http://www.it1352.com/429181.html 问题 我尝试通过MailKit访问一个IMAP账号,我设法下载邮件(作为的MimeMessage),并在某些时候我需要转发给其 ...

  2. Beta 冲刺(5/7)

    目录 摘要 团队部分 个人部分 摘要 队名:小白吃 组长博客:hjj 作业博客:beta冲刺(5/7) 团队部分 后敬甲(组长) 过去两天完成了哪些任务 ppt制作中 数据集标注 接下来的计划 制作p ...

  3. Laravel-google-authenticator--Google验证码

    开发前的准备 安装Laravel 安装二维码生成器QrCode,没有安装也可以,接下来会安装 安装拓展 1.运行如下代码安装拓展包: composer require "earnp/lara ...

  4. 部署自建CA颁发证书实现https加密

    理论忽略:百度上很多 需求:自建证书并实现域名的https加密 部署: 在linux机器上执行以下命令生成私钥 mkdir -p /opt/ssl-cert cd  /opt/ssl-cert 1.# ...

  5. Nginx负载-nginx转发到Swoole服务器(nginx配置文件变更)

  6. Python之copy模块

    概念 官方解释:Python中的赋值语句不复制对象,它们在目标和对象之间建立索引.对于可变项目或可变项目的集合,有时需要一个副本,以便可以更改一个副本而不更改其他副本.该模块提供通用的浅层和深层cop ...

  7. Javal连接字符串为Json

    public static String concatJson(String[] keys,String[] values,String[] alreadyJsonKeys){ if(keys==nu ...

  8. Chrome插件触发web页面的事件

    Chrome插件中不能直接调用Web页面的元素js,原因是chrome插件的机制http://stackoverflow.com/questions/17819344/triggering-a-cli ...

  9. AES CBC PKCS7 C# C++

    c++算法见:https://blog.csdn.net/csdn49532/article/details/50686222 c#:https://gitee.com/koastal/codes/6 ...

  10. 【Idea】idea code style配置eclipse code formatter

    在eclipse中有自动配置code style的功能 ,但是idea上却没有,这个时候需要自己手工配置 1. 在idea中找到Preference->Plugins->Browse re ...