我正在读一本关于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);
}
答案 0 :(得分:1)
每当您需要使用它时使用它......
在此示例中,作者正在使用它获取字符编码:
return "redirect:/contacts/" + UrlUtil.encodeUrlPathSegment(contact.getId().toString(), httpServletRequest);
以下是UrlUtil class的代码:
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
接口,为HTTP
servlet提供请求信息。如果您想要了解有关该类方法的更多信息,可以考虑阅读javadoc。