參數(shù)傳遞
ModelAndView傳遞
-
編寫controller
@Controller @RequestMapping("/account") public class AccountController { ? ? ?//也可以不創(chuàng)建ModelAndView,直接在參數(shù)中指定 ? ?@RequestMapping(value = "/findAccount9") ? ?public ModelAndView findAccount9(ModelAndView mv) { ? ? ? ?mv.addObject("msg", "歡迎你 springmvc"); ? ? ? ?mv.setViewName("success"); ? ? ? ?return mv; ? } }
-
在index.jsp里面定義超鏈接
<a href="/account/findAccount9">ModelAndView參數(shù)傳遞</a>
Model傳遞
-
編寫controller
@Controller @RequestMapping("/account") public class AccountController { ? ? ?@RequestMapping(value = "/findAccount10") ? ?public String findAccount10(Model model) { ? ? ? ?model.addAttribute("msg", "歡迎你 springmvc"); ? ? ? ?return "success"; ? } }
-
在index.jsp里面定義超鏈接
<a href="/account/findAccount10">Model參數(shù)傳遞</a>
ServletAPI傳遞
-
編寫controller
@Controller @RequestMapping("/account") public class AccountController { ? ? ?@RequestMapping("/findAccount11") ? ?public String findAccount11(HttpServletRequest request, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?HttpServletResponse response){ ? ? ? ?request.setAttribute("msg","歡迎你 springmvc"); ? ? ? ?return "success"; ? } }
-
在index.jsp里面定義超鏈接
<a href="/account/findAccount11">ServletAPI傳遞</a>
JSON數(shù)據(jù)處理
添加json依賴
springmvc 默認(rèn)使用jackson作為json類庫,不需要修改applicationContext-servlet.xml任何配置,只需引入以下類庫springmvc就可以處理json數(shù)據(jù):
<!--spring-json依賴--> <dependency> ? ?<groupId>com.fasterxml.jackson.core</groupId> ? ?<artifactId>jackson-databind</artifactId> ? ?<version>2.9.0</version> </dependency>
注解
-
@RequestBody:作用是接收前端ajax傳遞給后端的json字符串,并將json格式的數(shù)據(jù)轉(zhuǎn)為java對象
-
@ResponseBody:作用是將java對象轉(zhuǎn)為json格式的數(shù)據(jù)傳遞給前臺ajax
案例
-
編寫controller
@Controller @RequestMapping("/account") public class AccountController { ? ? ?@RequestMapping("/saveAccount2") ? ?@ResponseBody ? ?public Map saveAccount2(@RequestBody Account account){ ? ? ? ?Map<String, Object> map = new HashMap<String, Object>(); ? ? ? ?map.put("status",200); ? ? ? ?map.put("msg",account); ? ? ? ?return map; ? } }
-
在index.jsp里面定義ajax請求
-
添加按鈕
<input type="button" value="測試ajax請求json和響應(yīng)json" id="testJson"/>
-
引入js庫文件
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
-
編寫ajax代碼文章來源:http://www.zghlxwxcb.cn/news/detail-821585.html
?<script type="text/javascript"> ? ?$(function(){ ? ? ?$("#testJson").click(function(){ ? ? ? ?$.ajax({ ? ? ? ? ?type:"post", ? ? ? ? ?url:"/account/saveAccount2", ? ? ? ? ?contentType:"application/json;charset=UTF-8", ? ? ? ? ?data:'{"id":1,"name":"張二狗","money":999.0}', ? ? ? ? ?success:function(data){ ? ? ? ? ? ?if(data.status == 200){ ? ? ? ? ? ? ?alert(data.msg.name); ? ? ? ? ? ? ?alert(data.msg.money); ? ? ? ? ? } ? ? ? ? } ? ? ? }) ? ? }); ? }) ?</script>
-
-
測試文章來源地址http://www.zghlxwxcb.cn/news/detail-821585.html
到了這里,關(guān)于Spring MVC 參數(shù)傳遞和JSON數(shù)據(jù)處理的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!