SpringMvc 中的实用工具类介绍(包括 ResponseEntity、 RestTemplate、WebUtils 等)

此部分内容将包含 ResponseEntity、 RestTemplate、WebUtils 等

 

1. ResponseEntity

① Sprring Mvc 中作为方法的返回值使用法

1
2
3
4
5
6
7
8
9
@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

1
2
3
4
5
6
7
8
9
@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");
    }
}

 ③ 文件下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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("文件不存在!");
    }
}

文件下载后自动删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<Object> download(@RequestParam String templetId) {
    try {
        File zipFile = templetFileService.download(templetId);
        InputStream inputStream = new FileInputStream(zipFile) {
            @Override
            public void close() throws IOException {
                super.close();
                Files.delete(zipFile.toPath());
            }
        };
        InputStreamResource resource = new InputStreamResource(inputStream);
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8")).body(resource);
    } catch (Exception e) {
        return ResponseEntity.badRequest().body("文件不存在!");
    }
}

④ 在 RestTemplate 中作为 getForEntity() 与 exchange()返回值被使用

1
2
3
4
ResponseEntity<String> entity = template.getForEntity("http://example.com", String.class);
String body = entity.getBody();
MediaType contentType = entity.getHeaders().getContentType();
HttpStatus statusCode = entity.getStatusCode();

 ⑤ 可以很方便地返回不同类型的结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@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

1
@CookieValue(value="myCookie", defaultValue="someValue",required=false)

设置 cookie (还可以直接在 response header 里添加)

1
2
3
4
5
6
7
8
9
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 中的对象

1
public String handle(@SessionAttribute User user) {

设置 RedirectAttributes 添加 FlashAttribute

1
2
3
4
5
6
7
8
9
10
11
12
13
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

① 操作 参数

1
2
3
String param
      = ServletRequestUtils.getStringParameter(
        request, "param", "DEFAULT");

② 操作  session 或 cookie

1
2
3
4
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

posted on   Lemo_wd  阅读(5458)  评论(1编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2017-10-02 python 解释器
2017-10-02 python 中的 print 函数与 list函数
2017-10-02 python 中的流程控制语句
2017-10-02 python 中 打印及格式化字符串的相关方法
2017-10-02 python 中 try ...except
2017-10-02 python 中面向对象的概念
2017-10-02 python 多返回值
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示