controller使用map接收參數注意事項
關于前端使用map去接收參數的問題
1
2
3
4
5
6
7
|
@PostMapping ( "test01" ) @ResponseBody // 如果這里不加@RequestBody,那么springmvc默認創(chuàng)建的是BindAwareModelMap public Object test01( Map dataMap) { // 對象,并且都參數都不會封裝進去 System.out.println(dataMap); dataMap = null ; return new BindingAwareModelMap(); // 如果返回BindingAwareModelMap對象,就會拋出異常 } |
正確封裝姿勢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) { // 并且參數都封裝了進去(url路徑參數和json參數都會封裝進去) System.out.println(dataMap); dataMap.put( "msg" , "ojbk" ); return dataMap; } } |
結論:如果使用map接收前端參數,那么一定要加@Requestbody才行
1
2
3
4
5
|
#mybatis使用map封裝參數, @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); |
正確封裝姿勢2
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Data public class Page { private Map dataMap = new HashMap(); // 這里可以不用初始化,加了@RequestBody,默認創(chuàng)建LinkdedHashMap } @Controller @RequestMapping ( "map" ) public class MapController { @PostMapping ( "test01" ) @ResponseBody public Object test01( @RequestBody Page page) { // 一定要加@RequestBody,否則封裝不進去 return page; } } |
前端需要使用json傳參格式:
1
2
3
4
5
|
{ "dataMap" :{ "name" : "zzhua" } } |
controller使用map接收參數并用POSTman測試
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 , "列表條件查詢失敗" ); } } |
使用postman測試
controller使用map接收參數時必須使用 @RequestBody接收參數,否則后臺會出現接收不到的情況
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_16992475/article/details/107179019