参数在前台通过对象的形式传递到后台,在后台,可以用@RequestBody注解通过Map或JSONObject接收(太麻烦,既要从Map中取值,取完值后又要封装到Map),也可以用@RequestParam注解通过具体的属性接收。在dao层可以通过Map将参数传递到mapper.xml,也可以用@Param注解将具体的属性值传递到Mapper.xml。
@RequestParam语法:
语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)
1、value:参数名,
2、required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
示例:如果像下面这样写,当你清空(点击X号)省市区划时,会触发change事件,
<el-select v-model="listQuery.provinceCode" style="width: 160px;" placeholder="请选择省" @change="provinceChange" filterable clearable> <el-option v-for="item in provinceList" :key="item.id" :label="item.chiShortName" :value="item.id" /> </el-select>
provinceChange方法:
//根据省查询市 provinceChange(value) { console.log(value) if (this.listQuery.cityCode != undefined) { this.listQuery.cityCode = ''; }; if (this.listQuery.areaCode != undefined) { this.listQuery.areaCode = ''; }; const query = { 'pid': value } area.selectCityByPid(query).then(response => { console.log(response) this.cityList = response.data; }); },
由于pid值为空,故会报错。
@RequestMapping("/selectCity") public Result findAreasByPCity(@RequestParam(name = "pid") String pid) { return areaCodeService.findCityByPid(pid); }
故修改如下:
@RequestMapping("/selectCity") public Result findAreasByPCity(@RequestParam(name = "pid", required = false) String pid) { return areaCodeService.findCityByPid(pid); }
3、defaultValue:默认参数值,如果没有传该参数,就使用默认值
@RequestParam(name = "page", defaultValue = "1") int pageIndex,
在写接口时:加或不加@RequestParam注解的区别:
加@RequestParam为必传,因为required值默认是true,所以默认必传。可以通过@RequestParam(required = false)设置为非必传。
不加@RequestParam为非必传。
实例如下:
@PostMapping("/list") @ResponseBody public Result getCompanyInfoList(@RequestParam Integer page, Integer limit, String enterpiseType, String enterpriseName, String enterpiseCode, String organizationCode) { Result rs = new Result(); try{ PageHelper.startPage(page, limit); List<Map<String, Object>> select = enterpriseService.queryEnterpriseList(enterpiseType, enterpriseName, enterpiseCode, organizationCode, 0, limit); PageInfo p = new PageInfo<>(select); rs.setData(p); rs.setCode(ResultCode.SUCCESS); }catch (Exception e){ rs.setCode(ResultCode.FAILURE); logger.error(e.getMessage()); } return rs; }
只有page为必传,其他都为非必传。
前端代码:
前端传递给后台一个对象。
data() {
return {
listQuery: {
page: 1,
limit: 20,
dataCode: null,
dataName: null,
// enterpriseId: null,
enterpriseType: null
},
},
getList() { this.listLoading = true dataSet.getList(this.listQuery).then(response => { if (response.success) { this.list = response.data this.total = response.total } else { this.$message.error("数据集合信息获取失败") } }).catch(error => { console.log(error) this.$message.error("发生内部错误,请联系管理员") }).finally(() => { this.listLoading = false }) },
getList(query) { return request({ url: '/dataSet/list', method: 'post', params: query }) },
后台代码:
controller:
controller用@RequestParam注解接收单个属性
@RestController @RequestMapping("api/dataSet") @Validated public class DataSetController { private static Logger logger = LoggerFactory.getLogger(DataSetController.class); @Autowired private DataSetService dataSetService; @PostMapping("/list") public Result getDataSetList( @RequestParam(required = false) String dataCode, @RequestParam(required = false) String dataName, @RequestParam(name = "page", defaultValue = "1") int pageIndex, @RequestParam(name = "limit", defaultValue = "10") int length ) { return dataSetService.getDataSetList(dataCode, dataName, pageIndex, length); } }
也可以用Map或JSONObject接收前端传递过来的整个对象
@RestController
@RequestMapping("api/dataSet") @Validated public class DataSetController { private static Logger logger = LoggerFactory.getLogger(DataSetController.class); @Autowired private DataSetService dataSetService; @PostMapping("/list") public Result getDataSetList(@RequestBody Map map ) {
String dataCode = (String) map.get("dataCode");
String dataName = (String) map.get("dataName");
Integer pageIndex = (Integer) map.get("pageIndex");
Integer length = (Integer) map.get("length");
return dataSetService.getDataSetList(dataCode, dataName, pageIndex, length); } }
@RestController @RequestMapping("api/dataSet") @Validated public class DataSetController { private static Logger logger = LoggerFactory.getLogger(DataSetController.class); @Autowired private DataSetService dataSetService; @PostMapping("/list") public Result getDataSetList(@RequestBody JSONObject map ) { String dataCode = map.getString("dataCode"); String dataName = map.getString("dataName"); Integer pageIndex = map.getIntValue("pageIndex"); Integer length = map.getIntValue("length"); return dataSetService.getDataSetList(dataCode, dataName, pageIndex, length); } }
service:
service中可以将参数封装到Map中再传递到dao层,即使是controller层用Map接收,service层中也要从Map中取值。
public Result getDataSetList(String dataCode, String dataName, int pageIndex, int length) {
Map map = new HashMap();
map.put("dataCode", dataCode);
map.put("dataName", dataName);
PageHelper.startPage(pageIndex, length);
List<Map> dataSetList = dataSetMapper.selectDataSetList(map);
PageInfo pageInfo = new PageInfo(dataSetList);
return Result.operating("数据集合查询成功", true, Result.SUCCESS, pageInfo.getList(), (int) pageInfo.getTotal(), pageInfo.getPages());
}
service中也可以直接将参数分别传递到dao层
public Result getDataSetList(String dataCode, String dataName, int pageIndex, int length) { PageHelper.startPage(pageIndex, length); List<Map> dataSetList = dataSetMapper.selectDataSetList(dataCode,dataName); PageInfo pageInfo = new PageInfo(dataSetList); return Result.operating("数据集合查询成功", true, Result.SUCCESS, pageInfo.getList(), (int) pageInfo.getTotal(), pageInfo.getPages()); }
dao层:
官方介绍:如果你的映射方法接受多个参数,就可以使用这个注解自定义每个参数的名字。否则在默认情况下,除RowBounds以外的参数会以 "param" 加参数位置被命名。例如 #{param1}, #{param2}。如果使用了 @Param("person"),参数就会被命名为 #{person}。
@Param(该注解属于MyBatis)作为Dao层的注解,作用是用于传递参数,从而可以与SQL中的的字段名相对应,一般在2=<参数数<=5时使用最佳。
使用方式:
1.传递单个参数时,不需要使用@Param,因为传进去一个值,也只有一个参数与之匹配(当然也可以用@Param)。
2.传递多个参数时,使用@Param可以进行参数的绑定(当然也可以不用,可以封装JavaBean或者使用Map传值)。
@Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中。
(1)、如果service中将参数封装到Map中再传递到dao层,则dao层用Map
public interface DataSetMapper extends Mapper<DataSet> { List<Map> selectDataSetList(Map map); }
(2)、如果service中直接将参数分别传递到dao层,则用@Param注解接收
public interface DataSetMapper extends Mapper<DataSet> { List<Map> selectDataSetList(@Param("dataCode") String dataCode,@Param("dataName") String dataName); }
mapper.xml:
<select id="selectDataSetList" resultType="java.util.Map">
SELECT
t1.id AS "dataId",
t1.data_code AS "dataCode",
t1.data_name AS "dataName",
t1.remark AS "remark",
t2.id AS "enterpriseDataSetId",
t3.id AS "enterpriseId",
t3.enterprise_name AS "enterpriseName"
FROM
sys_data_set t1
LEFT JOIN sys_enterprise_data_set t2 ON t1.id = t2.data_id
LEFT JOIN sys_enterprise t3 ON t2.enterprise_id = t3.id
WHERE 1=1 AND t1.status=0
<if test="dataCode!=null and dataCode!=''">
AND t1.data_code LIKE '%'||#{dataCode}||'%'
</if>
<if test="dataName!=null and dataName!=''">
AND t1.data_name LIKE '%'||#{dataName}||'%'
</if>
<if test="enterpriseId!=null and enterpriseId!=''">
AND t3.del_flag = 0
AND t3.id=#{enterpriseId}
</if>
ORDER BY t1.id DESC
</select>
使用@Param给参数命名为其他名字
List<Menu> getMenuList(@Param("menuId") Integer parentId);
mapper.xml
<select id="getMenuList" resultMap="result_SysMenu_Map"> select * from sys_menu <if test="menuId != null and menuId !='' ">where parent_id=#{menuId}</if> <if test="menuId == null or menuId =='' ">where parent_id =0</if> order by order_num </select>
(3)、不使用@Param注解时,最好传递 Javabean。在SQL语句里就可以直接引用JavaBean的属性,而且只能引用JavaBean存在的属性。
Mapper接口方法:
public int getUsersDetail(User user);
对应Sql Mapper.xml文件:
<!--这里直接引用对象属性即可,不需要对象.属性的方式--> <select id="getUserDetail" statementType="CALLABLE" resultMap="baseMap"> Exec WebApi_Get_CustomerList #{userid} </select>