JavaWeb学习之路——SSM框架之SpringMVC(九)
SpringMVC跳轉(zhuǎn)、視圖解析器和@ResponseBody的用法
1.跳轉(zhuǎn)方式
(1)默認(rèn)方式字符串內(nèi)容來轉(zhuǎn)發(fā)
(2)設(shè)置返回值內(nèi)容轉(zhuǎn)發(fā)
? ? ? ? ?添加redirect:資源路徑·? 重定向
? ? ? ? ?添加forward:資源路徑?或省略? 轉(zhuǎn)發(fā)
??@RequestMapping("demo4")public String demo4() {System.out.println("轉(zhuǎn)發(fā)");return "redirect:/images/test.jsp";}2.視圖解析器
(1)Spring會(huì)提供默認(rèn)視圖解析器
(2)自定義視圖解析器,在springmvc.xml中自己配置ViewResolver,下面表示在根目錄下的所有jsp文件可省略文件格式
?<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/"></property><property name="suffix" value=".jsp"></property></bean>這里的返回視圖不帶.jsp文件也能返回了
(3)如果希望不執(zhí)行自定義視圖解析器,可以在方法返回值前面添加forward:或redirect:
?????public String demo4() {System.out.println("轉(zhuǎn)發(fā)");return "forward:demo5";}@RequestMapping("demo5")public String demo5() {System.out.println("轉(zhuǎn)發(fā)2");return "main";}?
3.@ResponseBody。它用來返回JSON數(shù)據(jù)或者是XML數(shù)據(jù),需要注意的呢,在使用此注解之后不會(huì)再走試圖處理器,而是直接將數(shù)據(jù)寫入到輸入流中,他的效果等同于通過response對(duì)象輸出指定格式的數(shù)據(jù)。
@RequestMapping("login")@ResponseBodypublic User login(User user){return user;}User字段:userName pwd
那么在前臺(tái)接收到的數(shù)據(jù)為:'{"userName":"xxx","pwd":"xxx"}'
效果等同于如下代碼:
@RequestMapping("login")public void login(User user, HttpServletResponse response){response.getWriter.write(JSONObject.fromObject(user).toString());}?
(1)在方法上只有@RequestMapping時(shí),無論方法返回值是什么,他都會(huì)返回到j(luò)sp界面
(2)在方法上添加@ResponseBody后
如果返回值滿足key-value形式(對(duì)象或map),把響應(yīng)頭設(shè)置為application/json;charset=utf-8,然后把轉(zhuǎn)換后的內(nèi)容輸出流的形式響應(yīng)給客戶端,不會(huì)返回到相應(yīng)視圖。若不滿足key-value,把響應(yīng)頭設(shè)置為text/html;charset=utf-8 ,produces表示content-type取值。????
?@RequestMapping(value="demo6",produces="application/json;charset=utf-8")@ResponseBodypublic Flower demo6() {Flower flower=new Flower();flower.setId(1);flower.setName("rose");return flower;}@RequestMapping("demo7")public String demo7() {Flower flower=demo6();System.out.println(flower.getName()+" "+flower.getId());return "main";}測試結(jié)果:
?
?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的JavaWeb学习之路——SSM框架之SpringMVC(九)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaWeb学习之路——SSM框架之S
- 下一篇: hashmap实现倒排索引——查询多个单