首页 > 解决方案 > @PathVariable 不适用于非拉丁语言

问题描述

我有一个从数据库中获取 Post 的控制器方法。

@RequestMapping(value = {"/post/{id}", "/post/{id}/{title}"}, method = RequestMethod.GET)

post 表在数据库中如下所示:

当我收到从数据库获取帖子的 GET 请求时,我从数据库中获取帖子并检查 URL 中的标题 slug 是否与数据库中的 slug 匹配,如果它们相同,我将显示它,如果不是,我会将请求重定向到与数据库中的 slug 相同的方法。

我尝试了以下代码

@RequestMapping(value = {"/post/{id}", "/post/{id}/{title}"}, method = RequestMethod.GET)
public String getPost(@PathVariable("id") Long id, 
        @PathVariable("title") Optional<String> title,
        Model model,
        HttpServletRequest request) {

    Optional<PostDTO> postDTO = postService.findOne(id);
    if(postDTO.isPresent()) {
        String slug = postDTO.get().getSlug();

        model.addAttribute("post", postDTO.get());

        if( (title.isPresent() && !slug.equals(title.get())) || !title.isPresent()) {
            // redirect
            return "redirect:/post/" + postDTO.get().getId() + "/" + slug;
        } else {
            return "post/index";
        }
    } else {
        return "post/not_found";
    }
}

但是当它到达重定向语句时,发送了 id,但标题为空,所以我得到一个无限循环。

我做错了什么?

更新:

经过一些调试,我发现如果存储在 slug 变量中的文本是英语,我的代码工作正常,但如果它是阿拉伯语,它将为空。

return "redirect:/post/" + postDTO.get().getId() + "/" + slug;

return "redirect:/post/" + postDTO.get().getId() + "/" + "Hello"; // working fine
return "redirect:/post/" + postDTO.get().getId() + "/" + "مرحبا"; // not working

不工作意味着@PathVariable("title") Optional<String> title重定向后将为空。

标签: javaspring-mvcredirectseo

解决方案


推荐阅读