日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringMVC那点事

發(fā)布時(shí)間:2025/3/8 javascript 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringMVC那点事 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、SpringMVC返回json數(shù)據(jù)的三種方式

1、第一種方式是spring2時(shí)代的產(chǎn)物,也就是每個(gè)json視圖controller配置一個(gè)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工具將對(duì)象序列化成json,常用工具Jackson,fastjson,gson。

3、第三種利用spring mvc3的注解@ResponseBody,然后使用spring mvc的默認(rèn)配置就可以返回json了。

  即return Object 會(huì)自動(dòng)轉(zhuǎn)換成JSON對(duì)象。

二、springMVC對(duì)于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;}

  對(duì)于ModelAndView構(gòu)造函數(shù)可以指定返回頁面的名稱,也可以通過setViewName方法來設(shè)置所需要跳轉(zhuǎn)的頁面;

2.Model

  一個(gè)模型對(duì)象,主要包含spring封裝好的model和modelMap,以及java.util.Map,當(dāng)沒有視圖返回的時(shí)候視圖名稱將由requestToViewNameTranslator決定;

3.ModelMap

待續(xù)

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相當(dāng)于request.setAttribute方法return map;}

   響應(yīng)的view應(yīng)該也是該請(qǐng)求的view。等同于void返回。

5.View

  這個(gè)時(shí)候如果在渲染頁面的過程中模型的話,就會(huì)給處理器方法定義一個(gè)模型參數(shù),然后在方法體里面往模型中添加值。

6.String

  對(duì)于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來將內(nèi)容或者對(duì)象作為HTTP響應(yīng)正文返回(適合做即時(shí)校驗(yàn));

@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));     }

  返回字符串表示一個(gè)視圖名稱,這個(gè)時(shí)候如果需要在渲染視圖的過程中需要模型的話,就可以給處理器添加一個(gè)模型參數(shù),然后在方法體往模型添加值就可以了。如果返回的是對(duì)象則會(huì)產(chǎn)生一個(gè)默認(rèn)的視圖,然后將返回的對(duì)象直接解析成JSON,默認(rèn)視圖+JSON生成正文返回。

7.Void

  當(dāng)返回類型為Void的時(shí)候,則響應(yīng)的視圖頁面為對(duì)應(yīng)著的訪問地址

@Controller @RequestMapping(value="/type") public class TypeController extends AbstractBaseController{@RequestMapping(method=RequestMethod.GET)public void index(){ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("xxx", "xxx");} }

  返回的結(jié)果頁面還是:/type

  這個(gè)時(shí)候我們一般是將返回結(jié)果寫在了HttpServletResponse?中了,如果沒寫的話,spring就會(huì)利用RequestToViewNameTranslator?來返回一個(gè)對(duì)應(yīng)的視圖名稱。如果這個(gè)時(shí)候需要模型的話,處理方法和返回字符串的情況是相同的。

三、Jackson json 處理全大寫或不規(guī)范的JSON

  通過對(duì)API的研究可以通過@JsonProperty以及@JsonAutoDetect來實(shí)現(xiàn)。

  具體參考: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接收J(rèn)SON對(duì)象

  我做的是將form的數(shù)據(jù)轉(zhuǎn)成json數(shù)據(jù),然后發(fā)送到后臺(tái),后臺(tái)是SpringMVC。

  SpringMVC

<mvc:annotation-driven><mvc:message-converters register-defaults="true"><!-- 將StringHttpMessageConverter的默認(rèn)編碼設(shè)為UTF-8 --><bean class="org.springframework.http.converter.StringHttpMessageConverter"><constructor-arg value="UTF-8" /></bean><!-- 將Jackson2HttpMessageConverter的默認(rèn)格式化輸出設(shè)為true --><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><property name="prettyPrint" value="true"/></bean> </mvc:message-converters></mvc:annotation-driven>

  注意:這兩個(gè)Converter很是重要,他們可以幫助我們將Json數(shù)據(jù)轉(zhuǎn)換成java對(duì)象。

?

  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(); //自動(dòng)將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);}}); }

?

  開始的時(shí)候總是出現(xiàn)?400 (Bad Request)這個(gè)錯(cuò)誤,? 出現(xiàn)這個(gè)錯(cuò)誤的原因一般最常見的就是后臺(tái)的實(shí)體類bean與前臺(tái)穿過的類型不匹配。然后我打印了一下上述方式生成的json,發(fā)現(xiàn)數(shù)據(jù)格式竟然是這樣子的:

[{"name":"phoneNumber","value":""},{"name":"eMail","value":""},{"name":"appId","value":""},{"name":"title","value":""},{"name":"content","value":""},{"name":"isMailtTemplate","value":"false"}]

  相信如果不仔細(xì)看的話,還以為是對(duì)的。仔細(xì)一看,怎么表單的name屬性和value屬性怎么出現(xiàn)在這個(gè)Json對(duì)象里了。這怎么能成功的和后臺(tái)交互呢?

  于是改了一下,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));}}); }

  最終打印的數(shù)據(jù):

  {"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數(shù)據(jù)解析

  <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>

 

?

  后臺(tái)自定義Bean (注意:不要寫成內(nèi)部類,要寫成單獨(dú)的一個(gè)類。內(nèi)部類可能報(bào)錯(cuò),Json轉(zhuǎn)對(duì)象失敗:"No suitable constructor found for type [simple type, class com.test.faster.domain.respons ,即使定義了構(gòu)造方法。

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;} }

??

?

轉(zhuǎn)載于:https://www.cnblogs.com/hujunzheng/p/5293050.html

總結(jié)

以上是生活随笔為你收集整理的SpringMVC那点事的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。