此部分内容将包含 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. 【转】Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position 0-1

    转自:https://blog.csdn.net/AckClinkz/article/details/78538462 环境 >>> import sys >>> ...

  2. MVC 前端页面ViewData参数名不区分大小写

    项目中实际应用: 后台赋值时传的是:ViewData["CheckedSystemMenu"], 前台取值时:ViewData["checkedsystemmenu&qu ...

  3. CentOS Android Studio桌面图标的创建

    1.切换到root用户,在桌面上创建Android.Studio.desktop,如下: [Desktop Entry] Name=Android Studio Comment=Android Stu ...

  4. No grammar constraints (DTD or XML Schema) referenced in the document.

    问题描述 web.xml 使用 Servlet4.0 版本,No grammar constraints (DTD or XML Schema) referenced in the document. ...

  5. electron Windows和mac 的菜单栏隐藏

    1.Windows隐藏方法 const {electron,Menu,debug} = require('electron'); Menu.setApplicationMenu(null) 2.mac ...

  6. SQL语句:子查询

    一,子查询定义: 子查询就是嵌套在主查询中的查询. 子查询可以嵌套在主查询中所有位置,包括SELECT.FROM.WHERE.GROUP BY.HAVING.ORDER BY. 但并不是每个位置嵌套子 ...

  7. cocos creator 动画编辑器以及骨骼动画的使用

    一.普通动画的设置 1.添加动画组件 a.添加空节点=>添加动画组件 b.新建Clip文件=>打开编辑模式添加动画编辑(并且把添加的clip文件拖动到右边面板的Default Clip 与 ...

  8. linux extglob模式 和rm反选

    前言 extglob模式开启之后Shell可以另外识别出5个模式匹配操作符,能使文件匹配更加方便. 不然不识别! 正文 #开启命令: shopt -s extglob #关闭命令: shopt -u ...

  9. video作为背景全屏铺满问题

    项目中我打算使用一个MP4视频作为登录界面背景,首先在静态页面都没法显示出来,后来发现需要将视频的编码格式转换为H264的格式方能正常显示(使用格式工厂转换即可): 后又发现视频没办法铺满全屏,在不同 ...

  10. Python3学习笔记十三

    1.   css 老师的博客:http://www.cnblogs.com/yuanchenqi/articles/6856399.html 选择器:找到想要改变的标签 css的功能:渲染和布局 2. ...