0

我正在阅读一本关于 spring 的书,在关于 spring mvc 的章节中,作者列出了以下负责表单提交的控制器代码。我的问题(因为作者没有提到它是我们应该使用HttpServletRequest的原因和位置)这是方法:

@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.POST)
    public String update(@Valid Contact contact, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale)
    {
        logger.info("Updating contact");

        if (bindingResult.hasErrors())
        {
            uiModel.addAttribute("message", new Message("error", messageSource.getMessage("contact_save_fail", new Object[]{}, locale)));
            uiModel.addAttribute("contact", contact);
            return "contacts/update";
        }

        uiModel.asMap().clear();
        redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("contact_save_success", new Object[]{}, locale)));
        contactService.save(contact);
        return "redirect:/contacts/" + UrlUtil.encodeUrlPathSegment(contact.getId().toString(), httpServletRequest);
    }
4

1 回答 1

1

在您需要使用它时使用它...

在这个例子中,作者使用它来获取字符编码:

return "redirect:/contacts/" + UrlUtil.encodeUrlPathSegment(contact.getId().toString(), httpServletRequest);

这是UrlUtil 类的代码:

public class UrlUtil {
    public static String encodeUrlPathSegment(String pathSegment, HttpServletRequest
            httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
        }
        return pathSegment;
    }
}

有关课程的更多信息HttpServletRequest

它扩展了ServletRequest接口以提供HTTPservlet 的请求信息。如果您想了解有关该类方法的更多信息,可以考虑阅读javadoc 。

于 2013-07-09T19:02:13.497 回答