Spring in action 閱讀筆記3

5.3接受請求的輸入

@RequestParam(value="", defaultValue="") long max
盡管defaultValue是String類型的值,但是綁定到max參數時,會轉換成Long類型

"/spittles/12345" vs "/spittles/show?spittle_id=12345"
前者能夠識別出要查詢的資源,后者描述的是帶有參數的一個操作-本質上是通過HTTP發起的RPC

7.1配置的替代方案

添加其他的Servlet與Filter
實現WebApplicationInitializer,注冊其他組件

7.2Multipart
  1. MultipartResolver
    A. StandardServletMultipartResolver 配置信息在DispatcherServlet之中
@Bean
public MultipartResolver multipartResolver() throws IOException {
return new StandardServletMultipartResolver();
}
// 1.WebApplicationInitializer
DispatcherServlet ds = new DispatcherServlet();
Dynamic registration = context.addServlet("appServlet", ds);
registration.addMapping("/");
registration.setMultipartConfig(
new MultipartConfigElement("/tmp/spittr/uploads"));
//
// 2.AbstractAnnotationConfigDispatcherServletInitializer
@Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(
new MultipartConfigElement("/tmp/spittr/uploads"));
}
//
// 3.web.xml
<servlet>
    <servlet-name>SpringDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <multipart-config>
        <location>/tmp</location>
        <max-file-size>5242880</max-file-size><!--5MB-->
        <max-request-size>20971520</max-request-size><!--20MB-->
        <file-size-threshold>0</file-size-threshold>
    </multipart-config>
</servlet>

B. CommonsMultipartResolver
只需要配置bean

@Bean
public MultipartResolver multipartResolver() throws IOException {
CommonsMultipartResolver multipartResolver =
new CommonsMultipartResolver();
multipartResolver.setUploadTempDir(
new FileSystemResource("/tmp/spittr/uploads"));
multipartResolver.setMaxUploadSize(2097152);
multipartResolver.setMaxInMemorySize(0);
return multipartResolver;
}

MultipartResolver在DispatcherServlet轉發請求之前對request進行處理,如果是Multipart的請求,就分解為MultipartHttpServletRequest

  1. 請求
    POST enctype="multipart/form-data"
    <input type="file" name="" accept="" />
  2. 處理Multipart請求
    A. @RequestPart("name") byte[] filebyte
    B. @RequestPart("name") MultipartFile/Part file
    [Facepalm][Facepalm]如果使用Part參數接收文件,就不需要配置MultipartResolver了
7.3異常處理
  • 使用@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Not Found")標注異常,將異常映射到狀態碼
  • 使用@ExceptionHandler(Exception.class)標注異常處理方法,處理同一個Controller中handle method(RequestMapping)拋出的此類異常
  • 使用@ControllerAdvice進行全局的異常處理,處理所有Controller拋出的此類異常
  • Any Spring bean declared in the DispatcherServlet’s application context that implements HandlerExceptionResolver will be used to intercept and process any exception raised in the MVC system and not handled by a Controller. The interface looks like this:

public interface HandlerExceptionResolver {

    /**
     * Try to resolve the given exception that got thrown during on handler execution,
     * returning a ModelAndView that represents a specific error page if appropriate.
     * <p>The returned ModelAndView may be {@linkplain ModelAndView#isEmpty() empty}
     * to indicate that the exception has been resolved successfully but that no view
     * should be rendered, for instance by setting a status code.
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the executed handler, or {@code null} if none chosen at the
     * time of the exception (for example, if multipart resolution failed)
     * @param ex the exception that got thrown during handler execution
     * @return a corresponding ModelAndView to forward to,
     * or {@code null} for default processing
     */
    ModelAndView resolveException(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容