javascript
SpringMVC那点事
一、SpringMVC返回json數據的三種方式
1、第一種方式是spring2時代的產物,也就是每個json視圖controller配置一個Jsoniew。
如:<bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>?
或者<bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
同樣要用jackson的jar包。
2、第二種使用JSON工具將對象序列化成json,常用工具Jackson,fastjson,gson。
3、第三種利用spring mvc3的注解@ResponseBody,然后使用spring mvc的默認配置就可以返回json了。
即return Object 會自動轉換成JSON對象。
二、springMVC對于controller處理方法返回值的可選類型
1.ModelAndView
@RequestMapping(method=RequestMethod.GET)public ModelAndView index(){ModelAndView modelAndView = new ModelAndView("/user/index");//指定viewNamemodelAndView.addObject("xxx", "xxx");return modelAndView;}@RequestMapping(method=RequestMethod.GET)public ModelAndView index(){ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("xxx", "xxx");modelAndView.setViewName("/user/index");//指定viewNamereturn modelAndView;}對于ModelAndView構造函數可以指定返回頁面的名稱,也可以通過setViewName方法來設置所需要跳轉的頁面;
2.Model
一個模型對象,主要包含spring封裝好的model和modelMap,以及java.util.Map,當沒有視圖返回的時候視圖名稱將由requestToViewNameTranslator決定;
3.ModelMap
待續
4.Map
@RequestMapping(method=RequestMethod.GET)public Map<String, String> index(){Map<String, String> map = new HashMap<String, String>();map.put("1", "1");//map.put相當于request.setAttribute方法return map;}響應的view應該也是該請求的view。等同于void返回。
5.View
這個時候如果在渲染頁面的過程中模型的話,就會給處理器方法定義一個模型參數,然后在方法體里面往模型中添加值。
6.String
對于String的返回類型,筆者是配合Model來使用的。
@RequestMapping(method = RequestMethod.GET)public String index(Model model) {String retVal = "user/index";List<User> users = userService.getUsers();model.addAttribute("users", users);return retVal;}或者通過配合@ResponseBody來將內容或者對象作為HTTP響應正文返回(適合做即時校驗);
@RequestMapping(value = "/valid", method = RequestMethod.GET)@ResponseBodypublic String valid(@RequestParam(value = "userId", required = false) Integer userId,@RequestParam(value = "logName") String strLogName) {return String.valueOf(!userService.isLogNameExist(strLogName, userId)); }返回字符串表示一個視圖名稱,這個時候如果需要在渲染視圖的過程中需要模型的話,就可以給處理器添加一個模型參數,然后在方法體往模型添加值就可以了。如果返回的是對象則會產生一個默認的視圖,然后將返回的對象直接解析成JSON,默認視圖+JSON生成正文返回。
7.Void
當返回類型為Void的時候,則響應的視圖頁面為對應著的訪問地址
@Controller @RequestMapping(value="/type") public class TypeController extends AbstractBaseController{@RequestMapping(method=RequestMethod.GET)public void index(){ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("xxx", "xxx");} }返回的結果頁面還是:/type
這個時候我們一般是將返回結果寫在了HttpServletResponse?中了,如果沒寫的話,spring就會利用RequestToViewNameTranslator?來返回一個對應的視圖名稱。如果這個時候需要模型的話,處理方法和返回字符串的情況是相同的。
三、Jackson json 處理全大寫或不規范的JSON
通過對API的研究可以通過@JsonProperty以及@JsonAutoDetect來實現。
具體參考:http://energykey.iteye.com/blog/2146445
| ALL? ??????????This pseudo-type indicates that all of real types are included |
| CREATOR? ??????????Creators are constructors and (static) factory methods used to construct POJO instances for deserialization |
| FIELD? ??????????Field refers to fields of regular Java objects. |
| GETTER? ??????????Getters are methods used to get a POJO field value for serialization, or, under certain conditions also for de-serialization. |
| IS_GETTER? ??????????"Is getters" are getter-like methods that are named "isXxx" (instead of "getXxx" for getters) and return boolean value (either primitive, or?Boolean). |
| NONE? ??????????This pseudo-type indicates that none of real types is included |
| SETTER? ??????????Setters are methods used to set a POJO value for deserialization. |
四、SpringMVC接收JSON對象
我做的是將form的數據轉成json數據,然后發送到后臺,后臺是SpringMVC。
SpringMVC
<mvc:annotation-driven><mvc:message-converters register-defaults="true"><!-- 將StringHttpMessageConverter的默認編碼設為UTF-8 --><bean class="org.springframework.http.converter.StringHttpMessageConverter"><constructor-arg value="UTF-8" /></bean><!-- 將Jackson2HttpMessageConverter的默認格式化輸出設為true --><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><property name="prettyPrint" value="true"/></bean> </mvc:message-converters></mvc:annotation-driven>注意:這兩個Converter很是重要,他們可以幫助我們將Json數據轉換成java對象。
?
Controler
@Controller @RequestMapping(value="/hjzgg/message") public class MessageDemo {@RequestMapping(method = RequestMethod.POST)public @ResponseBody String sendMessage(@RequestBody MyAddress myAddress, HttpServletRequest request){return "hjzgg";} }?
js
function sendMessage(){var formData = $("#messageForm").serializeArray(); //自動將form表單封裝成json console.log(JSON.stringify(formData));$.ajax({ type:"POST", url:"hjzgg/message", dataType:"json", contentType:"application/json", data:JSON.stringify(formData), success:function(response){ alert(response);},error:function(response){alert(response);}}); }?
開始的時候總是出現?400 (Bad Request)這個錯誤,? 出現這個錯誤的原因一般最常見的就是后臺的實體類bean與前臺穿過的類型不匹配。然后我打印了一下上述方式生成的json,發現數據格式竟然是這樣子的:
[{"name":"phoneNumber","value":""},{"name":"eMail","value":""},{"name":"appId","value":""},{"name":"title","value":""},{"name":"content","value":""},{"name":"isMailtTemplate","value":"false"}]
相信如果不仔細看的話,還以為是對的。仔細一看,怎么表單的name屬性和value屬性怎么出現在這個Json對象里了。這怎么能成功的和后臺交互呢?
于是改了一下,js如下:
function serializeJson(){var serializeObj={}; var array=$("#messageForm").serializeArray();$(array).each(function(){ if(serializeObj[this.name]){ if($.isArray(serializeObj[this.name])){ serializeObj[this.name].push(this.value); }else{ serializeObj[this.name]=[serializeObj[this.name],this.value]; } }else{ serializeObj[this.name]=this.value; } }); return serializeObj; }function sendMessage(){var formData = serializeJson();console.log(JSON.stringify(formData));$.ajax({ type:"POST", url:"hjzgg/message", dataType:"json", contentType:"application/json", data:JSON.stringify(formData), success:function(response){ alert(JSON.stringify(response));},error:function(response){alert(JSON.stringify(response));}}); }最終打印的數據:
{"phoneNumber":"","eMail":"","appId":"","title":"","content":"fsdfsd","isMailtTemplate":"false"}
這才是正解啊。
?
?
五、?fastjson 中的 SimplePropertyPreFilter(JSON的字段過濾)
http://blog.csdn.net/yongjiandan/article/details/8308793
Iterable<BaseEtype> baseEtypes = baseEtypeService.getBaseEtypes(enumId); SimplePropertyPreFilter filter = new SimplePropertyPreFilter(BaseEtype.class); filter.getExcludes().add("baseEnum"); String index = JSON.toJSONString(baseEtypes, filter);六、自定義Bean數據解析
<mvc:annotation-driven><mvc:message-converters register-defaults="true"><bean class="org.springframework.http.converter.StringHttpMessageConverter"><constructor-arg value="UTF-8" /><property name="writeAcceptCharset" value="false" /></bean><beanclass="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><property name="prettyPrint" value="true" /></bean></mvc:message-converters></mvc:annotation-driven>
?
后臺自定義Bean (注意:不要寫成內部類,要寫成單獨的一個類。內部類可能報錯,Json轉對象失敗:"No suitable constructor found for type [simple type, class com.test.faster.domain.respons ,即使定義了構造方法。)
public class SaveRoleAppBtnVO{private List<RoleAppBtnVO> vos;private String roleId;public List<RoleAppBtnVO> getVos() {return vos;}public void setVos(List<RoleAppBtnVO> vos) {this.vos = vos;}public String getRoleId() {return roleId;}public void setRoleId(String roleId) {this.roleId = roleId;} }??
?
轉載于:https://www.cnblogs.com/hujunzheng/p/5293050.html
總結
以上是生活随笔為你收集整理的SpringMVC那点事的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 养老金多少起投
- 下一篇: 荣盛石化是上市公司吗?