javascript
Spring MVC 实践 - Component
Spring MVC 實踐
標簽 : Java與Web
Converter
Spring MVC的數據綁定并非沒有任何限制, 有案例表明: Spring在如何正確綁定數據方面是雜亂無章的. 比如: Spring總是試圖用默認的語言區域將日期輸入綁定到java.util.Data, 如果想要使用不同的日期格式(format),就需要Converter的協助.
Spring提供了Converter接口來供開發者自定義Converter類:
/*** @since 3.0* @param <S> the source type* @param <T> the target type*/ public interface Converter<S, T> {T convert(S source); }- 自定義Converter:
- 配置
為了能夠讓Spring MVC使用我們自定義的Converter, 需要在配置文件中配置一個ConversionServiceFactoryBean:
然后為<annotation-driven/>配置conversion-service屬性:
<mvc:annotation-driven conversion-service="conversionService"/>注: 還可以使用FormattingConversionServiceFactoryBean來加載Converter, 由于其配置方法與ConversionServiceFactoryBean, 故在此就不再贅述.
- Controller
BindingResult參數中放置了Spring的所有綁定錯誤.
Interceptor
Spring MVC的攔截器類似于Servlet中的Filter(關于Filter,詳細可參考Servlet - Listener、Filter、Decorator),用于Controller進行預處理和后處理.
Spring提供了Interceptor接口來供開發者自定義Interceptor類:
public interface HandlerInterceptor {/*** 進入Controller方法前執行* 應用場景: 身份認證、身份授權等*/boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception;/*** 進入Controller方法后, 返回ModelAndView前執行* 應用場景: 將公共模型數據填充到ModelAndView、統一指定視圖等*/void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception;/*** 執行完Controller方法后執行* 應用場景: 統一日志處理、統一異常處理等*/void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception;}示例: 統計Controller執行耗時.
- 自定義Interceptor
- 配置
Upload
Spring MVC提供了對Servlet 3.0文件上傳的支持(關于Servlet 3.0文件上傳可參考博客Servlet - Upload、Download、Async、動態注冊).
Spring MVC提供了MultipartFile接口,上傳到應用中的文件都被包裝在一個MultipartFile對象中:
| String getName() | Return the name of the parameter in the multipart form. |
| String getOriginalFilename() | Return the original filename in the client’s filesystem. |
| long getSize() | Return the size of the file in bytes. |
| boolean isEmpty() | Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content. |
| String getContentType() | Return the content type of the file. |
| byte[] getBytes() | Return the contents of the file as an array of bytes. |
| InputStream getInputStream() | Return an InputStream to read the contents of the file from. |
| void transferTo(File dest) | Transfer the received file to the given destination file. |
在Servlet 3.0及更高版本的容器中進行文件上傳編程,總是圍繞著@MultipartConfig注解和Part接口,處理上傳文件的Servlet必須以@MultipartConfig注解標注, 但DispatcherServlet是Spring jar包已經編譯好的類, 無法進行修改,值得慶幸的是Servlet 3.0還可以使用部署描述符web.xml將一個Servlet變為MultipartConfig Servlet:
<servlet><servlet-name>mvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/mvc-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup><multipart-config><max-file-size>20848820</max-file-size><file-size-threshold>1048576</file-size-threshold></multipart-config> </servlet> <servlet-mapping><servlet-name>mvc</servlet-name><url-pattern>*.do</url-pattern> </servlet-mapping>此外, 在mvc-servlet.xml文件中配置一個MultipartResolver:
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>此時就可以進行文件上傳編程了:
@RequestMapping("/upload.do") public String upload(MultipartFile file) throws IOException {String name = file.getOriginalFilename();String fileName = String.format("/data/file/%s", name);file.transferTo(new File(fileName));return "file_upload"; }Exception
系統異常包含兩類: 預期異常、運行時異常RuntimeException.前者通過捕獲異常從而獲取異常信息,后者主要通過規范代碼開發、測試等手段減少運行時異常的發生.
基于Spring MVC的DAO、Service、Controller的異常都可以通過throw向上層拋出,最后統一由DispatcherServlet的異常處理器進行處理.
- 自定義異常
如果Controller/Service/DAO拋出此類異常說明是預期異常:
- 異常處理器
- error.vm
- 注冊異常處理器
JSON
JSON數據格式形式簡單, 解析方便, 因此常用在接口調用、HTML頁面中.
Spring MVC對其提供了如下支持:在Controller方法上添加@ResponseBody注解, Spring MVC會自動將Java對象轉換成JSON字符串輸出; 在方法形參上添加@RequestBody注解, Spring MVC會自動將JSON串轉換成Java對象:
@ResponseBody @RequestMapping("/user_json.do") public User userJSON(@RequestBody User user) {return user; }- fastjson
Spring MVC默認使用jackson對request/response進行JSON轉換,而在此我們選用性能更高的fastjson, 因此需要在<annotation-driven/>中另做配置.
首先, 使用fastjson需要在pom.xml中添加如下依賴:
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.7</version> </dependency>然后在mvc-servlet.xml中做如下配置:
<mvc:annotation-driven><mvc:message-converters register-defaults="false"><bean id="fastJsonHttpMessageConverter"class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value><value>application/json;charset=UTF-8</value></list></property><property name="features"><array value-type="com.alibaba.fastjson.serializer.SerializerFeature"><value>DisableCircularReferenceDetect</value></array></property></bean></mvc:message-converters> </mvc:annotation-driven>Other
1. POST Encoder
在web.xml配置一個編碼Filter可以解決POST亂碼問題:
<filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param> </filter> <filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern> </filter-mapping>2. GET Encoder
對于GET亂碼, 由于Tomcat 8.0之前版本默認使用ISO-8859-1編碼, 因此有兩種解決方案:
- 修改tomcat配置文件
修改tomcat配置文件server.xml設置編碼與工程編碼一致:
- 重新編碼
將經Tomcat編碼的內容解碼后再重新編碼為UTF-8:
注: Tomcat 8.0及更高版本的容器不用此配置.
3. Static Resources Mapping
如果將DispatherServlet配置成攔截所有請求<url-pattern>/</url-pattern>, 則必須額外配置靜態資源的映射規則, 否則Spring MVC會對像js/css之類的文件也做轉發.
Spring MVC使用<mvc:resources/>元素配置對靜態資源的映射:
總結
以上是生活随笔為你收集整理的Spring MVC 实践 - Component的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: uva 10801 Lift Hoppi
- 下一篇: Reveal.js:把你的 Markdo