亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用Spring,我可以創建一個可選的路徑變量嗎?

使用Spring,我可以創建一個可選的路徑變量嗎?

繁華開滿天機 2019-11-11 14:40:31
在Spring 3.0中,我可以有一個可選的path變量嗎?例如@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)public @ResponseBody TestBean testAjax(        HttpServletRequest req,        @PathVariable String type,        @RequestParam("track") String track) {    return new TestBean();}在這里我想/json/abc還是/json要調用相同的方法。一種明顯的解決方法是聲明type為請求參數:@RequestMapping(value = "/json", method = RequestMethod.GET)public @ResponseBody TestBean testAjax(        HttpServletRequest req,        @RequestParam(value = "type", required = false) String type,        @RequestParam("track") String track) {    return new TestBean();}然后/json?type=abc&track=aa或/json?track=rr將工作
查看完整描述

3 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

您不能具有可選的路徑變量,但是可以有兩個調用相同服務代碼的控制器方法:


@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)

public @ResponseBody TestBean typedTestBean(

        HttpServletRequest req,

        @PathVariable String type,

        @RequestParam("track") String track) {

    return getTestBean(type);

}


@RequestMapping(value = "/json", method = RequestMethod.GET)

public @ResponseBody TestBean testBean(

        HttpServletRequest req,

        @RequestParam("track") String track) {

    return getTestBean();

}


查看完整回答
反對 回復 2019-11-11
?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

如果您在使用Spring 4.1和Java 8,你可以使用java.util.Optional它支持@RequestParam,@PathVariable,@RequestHeader和@MatrixVariableSpring MVC中-


@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)

public @ResponseBody TestBean typedTestBean(

    @PathVariable Optional<String> type,

    @RequestParam("track") String track) {      

    if (type.isPresent()) {

        //type.get() will return type value

        //corresponds to path "/json/{type}"

    } else {

        //corresponds to path "/json"

    }       

}


查看完整回答
反對 回復 2019-11-11
?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

眾所周知,您還可以使用@PathVariable批注注入路徑變量的Map。我不確定該功能是否在Spring 3.0中可用或是否在以后添加,但是這是解決示例的另一種方法:


@RequestMapping(value={ "/json/{type}", "/json" }, method=RequestMethod.GET)

public @ResponseBody TestBean typedTestBean(

    @PathVariable Map<String, String> pathVariables,

    @RequestParam("track") String track) {


    if (pathVariables.containsKey("type")) {

        return new TestBean(pathVariables.get("type"));

    } else {

        return new TestBean();

    }

}


查看完整回答
反對 回復 2019-11-11
  • 3 回答
  • 0 關注
  • 549 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號