1. 在spring mvc中配置fastjson
<!-- 設置配置方案 --> <mvc:annotation-driven> <!-- 設置不使用默認的消息轉換器 --> <mvc:message-converters register-defaults="false"> <!-- 配置Spring的轉換器, 字符編碼 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" index="0"/> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/> <!--配置fastjson中實現HttpMessageConverter接口的轉換器--> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <!-- 加入支持的媒體類型:返回contentType --> <property name="supportedMediaTypes"> <list> <!-- 這里順序不能反,一定先寫text/html,不然ie下會出現下載提示 --> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <!--枚舉類型,對於返回List集合中引用同一個對象,忽略引用檢測【注意不要出現循環引用現象】--> <property name="features"> <list> <value>DisableCircularReferenceDetect</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
2. 使用方法
// 文章details @RequestMapping(value = "/detail", method = RequestMethod.GET) public String detail(Long id, Model model, HttpServletRequest request){ Article article = articleService.getArticleById(id, request); Teacher teacher = (Teacher) request.getSession().getAttribute("teacher"); if(teacher==null){ return "login.jsp"; } // role : 1-teacher ArticleZan zan = articleService.getZan(article.getArticle_id(), 1, teacher.getTe_id()); model.addAttribute("article", article); model.addAttribute("zan",zan); return "article/detail.jsp"; }
{"id":1} ->可以完成參數瘋轉
對於普通的參數,fastjson可以完成參數封裝和類型轉換。但是對於JSON數據中有數組就無能為力了:例如:
解決辦法:
@CrossOrigin(origins = "*", maxAge = 3600) @RequestMapping(value = "/getArticles") @ResponseBody public Object getArticles(Long[] id, @RequestBody JSONObject[] obj, HttpServletRequest request){ Set<Long> ids = new HashSet<>(); for (JSONObject o : obj) { ids.add(o.getLong("id")); } List<Article> articles = articleService.getArticles(ids, request); return articles; }
end