2013-07-09 86 views
0

我正在讀一本關於spring的書,並且在關於spring mvc的章節中,作者列出了負責提交表單的以下控制器代碼。 我的問題(因爲筆者是不是指這就是爲什麼當我們要使用的HttpServletRequest) 下面是方法:什麼時候在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); 
    } 

回答

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

相關問題