controller使用map接收參數(shù)注意事項(xiàng)
關(guān)于前端使用map去接收參數(shù)的問(wèn)題
1
2
3
4
5
6
7
|
@PostMapping ( "test01" ) @ResponseBody // 如果這里不加@RequestBody,那么springmvc默認(rèn)創(chuàng)建的是BindAwareModelMap public Object test01( Map dataMap) { // 對(duì)象,并且都參數(shù)都不會(huì)封裝進(jìn)去 System.out.println(dataMap); dataMap = null ; return new BindingAwareModelMap(); // 如果返回BindingAwareModelMap對(duì)象,就會(huì)拋出異常 } |
正確封裝姿勢(shì)1
1
2
3
4
5
6
7
8
9
10
11
|
@Controller @RequestMapping ( "map" ) public class MapController { @PostMapping ( "test01" ) @ResponseBody // 如果加了@RequestBody,那么創(chuàng)建的是LinkedHashMap public Object test01( @RequestBody Map dataMap) { // 并且參數(shù)都封裝了進(jìn)去(url路徑參數(shù)和json參數(shù)都會(huì)封裝進(jìn)去) System.out.println(dataMap); dataMap.put( "msg" , "ojbk" ); return dataMap; } } |
結(jié)論:如果使用map接收前端參數(shù),那么一定要加@Requestbody才行
1
2
3
4
5
|
#mybatis使用map封裝參數(shù), @Select ( "select * from t_product where pid = #{pid} or pname = #{pname}" ) List<Product> getByMap(Map map); #mybatisplus中有寫好的方法 List<T> selectByMap( @Param ( "cm" ) Map<String, Object> columnMap); |
正確封裝姿勢(shì)2
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Data public class Page { private Map dataMap = new HashMap(); // 這里可以不用初始化,加了@RequestBody,默認(rèn)創(chuàng)建LinkdedHashMap } @Controller @RequestMapping ( "map" ) public class MapController { @PostMapping ( "test01" ) @ResponseBody public Object test01( @RequestBody Page page) { // 一定要加@RequestBody,否則封裝不進(jìn)去 return page; } } |
前端需要使用json傳參格式:
1
2
3
4
5
|
{ "dataMap" :{ "name" : "zzhua" } } |
controller使用map接收參數(shù)并用POSTman測(cè)試
controller層
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@PostMapping ( "/xksq/getGjclByCondition" ) public ResultInfo getGjclByCondition( @RequestBody Map<String,Object> params,HttpServletRequest request){ Map<String,Object> map = new HashMap<>(); try { Integer iPageIndex = (Integer) params.get( "iPageIndex" ); Integer iPageSize = (Integer) params.get( "iPageSize" ); PageHelper.startPage(iPageIndex!= null ?iPageIndex: 1 ,iPageSize!= null ?iPageSize: 10 ); String username = JwtUtil.getUsername(request.getHeader( "token" )); Rfgcgl user = rfgcglMapper.selectOne( new QueryWrapper<Rfgcgl>().eq( "YHMC" , username)); if ( null ==user){ return ResultInfo.fail( 903 , "用戶不存在" ); } params.put( "qynbbh" ,user.getQyNbBh()); List<Map<String, Object>> gjclByCondition = clxxQysqMapper.getGjclByCondition(params); PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(gjclByCondition); map.put( "total" ,pageInfo.getTotal()); map.put( "datas" ,pageInfo); return ResultInfo.ok(map); } catch (Exception e){ e.printStackTrace(); return ResultInfo.fail( 901 , "列表?xiàng)l件查詢失敗" ); } } |
使用postman測(cè)試
controller使用map接收參數(shù)時(shí)必須使用 @RequestBody接收參數(shù),否則后臺(tái)會(huì)出現(xiàn)接收不到的情況
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/qq_16992475/article/details/107179019