最近在實現一個分頁查詢全部的用戶及其角色的功能時,遇到了406的問題,費了好長時間才解決,記錄一下解決方法。spring
先後端分離的項目,寫接口的時候我用到了swagger框架。先說下406是什麼意思?後端
406:請求的資源的內容特性沒法知足請求頭中的條件,於是沒法生成響應實體。實體格式由Content-Type頭定義的媒體類型決定瀏覽器
解釋一下:返回的消息頭瀏覽器沒法解釋,下面是兩種不一樣的消息頭:app
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.7</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.7</version> </dependency>
/** * 查詢全部用戶 * * @param pn * @return */ @SuppressWarnings("unchecked") @RequestMapping(value = "/userRoleList", method = RequestMethod.GET) @RequiresRoles(value = "超級管理員") @ResponseBody @ApiOperation(value = "查詢全部用戶", notes = "查詢全部用戶", httpMethod = "GET") public Msg UserRoleList(@RequestParam(value = "pn", defaultValue = "1") String pn, @RequestParam(value = "ps", defaultValue = "5") String ps) { // 1. 分頁查詢全部的用戶 PageHelper.startPage(Integer.parseInt(pn), Integer.parseInt(ps)); // 傳入頁碼,每頁大小 List<Admin> admins = adminService.findAll(); // 2. 根據用戶名查詢每一個用戶各自的角色 List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Admin admin : admins) { List<Role> roles = adminService.findRoles(admin.getAdminName()); //添加用戶 LinkedHashMap<String, Object> admin_roles = new LinkedHashMap<String,Object>(); admin_roles.put("id", admin.getId()); admin_roles.put("adminName", admin.getAdminName()); admin_roles.put("name", admin.getName()); admin_roles.put("createTime", admin.getCreateTime()); admin_roles.put("lastLoginTime", admin.getLastLoginTime()); admin_roles.put("locked", admin.getLocked()>0?true:false); //添加角色 List<String> roleName = new ArrayList<String>(); for (Role role : roles) { roleName.add(role.getName()); } admin_roles.put("roles", roleName); //將用戶及其角色存放的list中 list.add(admin_roles); } // 3. 分頁信息 PageInfo page = new PageInfo(admins); return Msg.success().add("list", list).add("total", page.getTotal()); }
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency>