将url premeter替换为基于路径的参数

时间:2017-11-28 17:05:28

标签: spring spring-mvc spring-boot

我有以下控制器,它接受一个可选的"页面"参数。

现在我的网址看起来像mysite.com/pittsburgh-listings?page=2

我希望网址看起来像这样,我怎么能实现这个目标呢?

mysite.com/pittsburgh-listings/2
mysite.com/pittsburgh-listings/3
etc..

我的控制器

@Controller
public class CityController {
    private static final int BUTTONS_TO_SHOW = 5;
    private static final int INITIAL_PAGE = 0;
    private static final int INITIAL_PAGE_SIZE = 40;
    private static final int[] PAGE_SIZES = { 5, 10, 20, 40 };

    private AdService adService;

    public CityController(AdService adService) {
        this.adService = adService;
    }

    @RequestMapping(value = "/{city:[\\w'-]+}-listings", method = RequestMethod.GET)
    public String city(@PathVariable("city") String city, Model model, @RequestParam("page") Optional<Integer> page) {
        Database db = new Database();
        model.addAttribute("city", city.replace("-", " "));
        System.out.println(city.replace("-", " "));

        // List<Ad> ads = adService.getPage(1, city.replace("-", " "));
        // model.addAttribute("ads", ads);

        int evalPageSize = INITIAL_PAGE_SIZE;
        int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1;
        Long cityId = null;
        try {
            cityId = db.getCityId(city.replace("-", " "));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Page<Ad> ads = adService.findAllPageable(new PageRequest(evalPage, evalPageSize, Sort.Direction.DESC, "id"),
                cityId);
        System.out.println("Ads: " + ads.getSize());
        Pager pager = new Pager(ads.getTotalPages(), ads.getNumber(), BUTTONS_TO_SHOW);

        model.addAttribute("ads", ads);
        model.addAttribute("selectedPageSize", evalPageSize);
        model.addAttribute("pageSizes", PAGE_SIZES);
        model.addAttribute("pager", pager);
        return "city";
    }
}

0 个答案:

没有答案