此部分内容将包含 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. Python学习笔记-CGI编程(如何在IIS上挂Python开发的Webservice)

    一.如何用Python开发一个简单的Webservice 利用python的cgi编程,可以传入参数将结果输出. 定义需要编码以及需要引用的模块 #conding=utf-8 #修正中文乱码 impo ...

  2. 基于XML搭建SpringMVC项目

    *如果你需要将应用部署到不支持Servlet3.0容器中 或者 你只是对web.xml情有独钟,那我们只能按照传统的方式,通过web.xml来配置SpringMVC. *搭建SpringMVC需要在w ...

  3. zimbra6同域名与同hostname与同系统异机恢复

    系统:redhat5.4_64 安装DNS:[root@test6 ~]# yum install bind -y[root@test6 ~]# yum install bind-chroot -y[ ...

  4. 7个提升Python程序性能的好习惯

    原文作者:爱coding,会编程的核电工程师. 个人博客地址:zhihu.com/people/zhong-yun-75-63 掌握一些技巧,可尽量提高Python程序性能,也可以避免不必要的资源浪费 ...

  5. Python教学课程分享

    一.Python基本语法 1.1整数,实数,复数 前言: Python编程环境及方法 在python底层环境中唤醒python对话,直接在python中输入指令对系统进行命令编程 随意打开一个记事本或 ...

  6. SpringBoot相关错误

    1.org.springframework.boot.builder.SpringApplicationBuilder.<init>([Ljava/lang/Object;)V 搭建spr ...

  7. vs 修改活动解决方案配置后无法调试,不生成pdb文件,“当前不会命中断点 还没有为该文档加载任何符号” 解决方法

    修改vs的活动解决配置后无法进行调试,比如在Release.Debug之后新增一个TEST,切换到test后就无法进行调试. 修改一下 项目属性->生成->高级 中“调试信息”改为 ful ...

  8. samba服务器一次排错

    在全局配置完,可用.配置区域配置的时候,添加一个共享的文件夹时, 使用testparm 命令去检查配置.发现path路径无法正确读出.在window上去访问,显示无法正常访问. 修改path的位置,放 ...

  9. kafka常规及几个重要的操作命令

    1. 查看所有topic kafka-topics.sh --zookeeper hadoop3 --list 2. 创建tooic及topic的partitioner ./kafka-topics. ...

  10. 记录几个爬取动态网页时的问题(下拉框,旧的元素无法获取,获取的源代码和f12看到的不一致,爬取延迟)

    更新.....这个动态网页其实直接抓取ajax请求就可以了,很简单,我之前想复杂了,虽然也实现了,但是效率极低,不过没关系,就当作是对Selenium的一次学习吧 1.最近在爬取一个动态网页,其中为了 ...