开发者社区 问答 正文

spring 能不能在方法内决定返回类型

这个是直接对应 index 模型
screenshot
这个是直接返回 index 字符串
screenshot
能不能在方法中控制他返回对应 index 模型还是返回 index 字符串
就是这2个合并
也就是 @ResponseBody 能不能只用在其他地方
如果是下面这样,他会把 title keywords description 直接加在 /login/ 地址栏直接显示,怎么让他不显示,直接就是 跳转到 /login/
screenshot

展开
收起
蛮大人123 2016-02-28 15:55:23 2083 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    感觉ResponseEntity可以解决题主的问题,但并不推荐这样做,下面只是一个例子。

    @RequestMapping("/entity")
    @ResponseBody
    public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
        System.out.println(requestEntity.getHeaders().getFirst("MyRequestHeader"));
        System.out.println(Arrays.toString(requestEntity.getBody()));
    
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("MyResponseHeader", "MyValue");
        return new ResponseEntity<>("Hello World", responseHeaders, HttpStatus.CREATED);
    }

    代码乱乱的,写着不顺心,改着还闹心。
    不如用headers区分一下,同一个URL不同headers映射到不同方法。
    比如:

    @RequestMapping(value = "/",method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE,headers = {"a=1"})
    public String index(Map<String, Object> map) {
        map.put("title", "");
        map.put("keywords", "");
        map.put("description", "");
    
        return "index";
    }
    
    @RequestMapping(value = "/",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE,headers = {"a=1"})
    @ResponseBody
    public Map indexJson(Map<String, Object> map) {
        map.put("title", "");
        map.put("keywords", "");
        map.put("description", "");
    
        return map;
    }
    2019-07-17 18:49:41
    赞同 展开评论
问答分类:
问答地址: