java - spring 能不能在方法内决定返回类型
PHP中文网
PHP中文网 2017-04-17 13:10:21
0
2
556

这个是直接对应 index 模型

java    @RequestMapping(value = "/")
    public String index(Map<String, Object> map) {
        map.put("title", "");
        map.put("keywords", "");
        map.put("description", "");

        return "index";
    }

这个是直接返回 index 字符串

java    @RequestMapping(value = "/")
    @ResponseBody
    public String index(Map<String, Object> map) {
        map.put("title", "");
        map.put("keywords", "");
        map.put("description", "");

        return "index";
    }

能不能在方法中控制他返回对应 index 模型还是返回 index 字符串

就是这2个合并

也就是 @ResponseBody 能不能只用在其他地方

如果是下面这样,他会把 title keywords description 直接加在 /login/ 地址栏直接显示,怎么让他不显示,直接就是 跳转到 /login/

java    @RequestMapping(value = "/")
    public String index(Map<String, Object> map) {
        map.put("title", "");
        map.put("keywords", "");
        map.put("description", "");

        return "redirect:/login/";
    }
PHP中文网
PHP中文网

认证0级讲师

全部回覆(2)
左手右手慢动作

感覺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;
}
巴扎黑

應該把/login設定成post請求

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!