springMVC使用@RequestMapping遇到的问题

来源:互联网 发布:杭电网络教学平台 编辑:程序博客网 时间:2024/06/14 03:04

1.简介@RequestMapping既可以定义Controller,也可以定义方法Controller中的方法,主要是用来映射url的请求路径

2.属性简介:

value:     指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);

method:  指定请求的method类型, GET、POST、PUT、DELETE等;

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回

params: 指定request中必须包含某些参数值是,才让该方法处理。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

3.测试使用时遇到的问题: 

  先看源代码:

@RequestMapping(value="/api/{wayName}")public void getData(@PathVariable String wayName,@RequestParam("appkey") int appkey,@RequestParam("type") int type){System.out.println("wayName:"+wayName+"--appkey:"+appkey+"--type:"+type);}@RequestMapping(value="/test")public void test(){System.out.println("test----------commmin");}
访问/api/test时报HTTP Status 404 -错误,访问/test时也会报HTTP Status 404 -错误,有时会报Circular view path [list]: would dispatch back to the current handler URL [/list] again错误,在网上查了资料,了解到每个controller在初始化,如果你没有声明viewResolver,spring会注册一个默认的viewResolver给controlller,这个viewResolver本人简单的理解就是一个呈现处理结果到前端的工具,如果你视图的路径和请求路径一样,就会出现死循环。或者你如果在你的方法中没有返回数据到前端,这两个错误都有可能会出现。所以最终的解决方法就是返回数据到前端,解决后的源码是:
@RequestMapping(value="/api/{wayName}")@ResponseBodypublic String getData(@PathVariable String wayName,@RequestParam("appkey") String appkey,@RequestParam("type") String type){return "wayName:"+wayName+"--appkey:"+appkey+"--type:"+type;}@RequestMapping(value="/test")public void test(HttpServletRequest request,HttpServletResponse response) throws IOException{response.getWriter().print("Hello World");}
其中@ResponseBody是表示返回的数据输出到输出流中。

参考博客:http://blog.csdn.net/wthfeng/article/details/52742830


0 0