您的位置:首页 > 编程语言 > Java开发

springmvc controller ajax 一些使用说明

2016-06-27 16:37 375 查看
springmvc中controller方法的参数有多种定义形式,记录并说明几种常用方式

第1种:

RequestMapping(“test1”)

String test1(String userName) {

}

说明:

1)要求方法参数名称和请求传递的参数名完全一致,

2)通过这种方式获取数据时SpringMVC调用了request的getParameterValues方法

3)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST

第2种:

RequestMapping(“test2”)

String test2(@RequestParam(“name”) String userName) {

}

说明:

1)和第2种方式相同,只是当方法参数名称和请求传递的参数名称不一致时,可以指定传递的参数名

第3种:

RequestMapping(“test3”)

String test3(User user) {

}

说明:

1)要求方法参数对象中的属性名称和请求传递的参数名完全一致,

2)通过这种方式获取数据时SpringMVC调用了request的getParameterValues方法

3)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST

第4种:

RequestMapping(“test4”)

String test4(@RequestBody User user) {

}

说明:

1)用来处理Content-Type: 为 application/json或者xml编码的内容,提交方式GET、POST

2)通过使用HandlerAdapter配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上

第5种:

RequestMapping(“test5/{id}”)

String test5(@PathVariable(“id”) String id) {

}

说明:

1)获取路径变量

第6种:

RequestMapping(“test6/{id}”)

String test6(Model model1, Map model2, ModelMap model3) {

}

说明:

1)暴露渲染视图需要的模型数据

2)3个变量实际上是同一个对象,使用的时候可以任选其中一种

第7种:

RequestMapping(“test7”)

String test7(HttpServletRequest req, HttpServletResponse res, HttpSession session) {

}

说明:

1)spring在调用方法时会自动给上面方法参数赋值,方法中可以直接使用

Springmvc中controller方法的返回值,常见的两种形式

1)使用ReponseBody返回json对象

2)返回String类型的视图名

3)返回ModelAndView对象

关于Ajax调用时的content-type

1)ajax调用时默认的content-type是 application/x-www-form-urlencoded

2)通过contest-type的设定,可以指定json格式,contentType: “application/json”

3)springmvc中controller方法获取参数的形式,content-type是密切相关的,不同的类型需要采用不同的方法,详见第一部分的说明
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: