请求406错误
在controller中定义了一个固定格式的返回类,但是没有写get,set方法,只有私有字段
public class R <T>{ private Integer code; private String msg; private T data; public static<T> R<T> success(T o){ R<T> r=new R<T>(); r.code=1; r.msg=""; r.data=o; return r; } public static<T> R<T> error(String str){ R r=new R(); r.code=0; r.msg=str; return r; } }
在controller 返回时候一直报错406状态码错误,实际原因是因为只有私有字段,所以无法被序列化返回,所以报错了
@Slf4j @RequestMapping("/employee") @RestController public class EmployeeController { @Autowired private EmployeeService employeeService; @PostMapping("/login") public R<Employee> login(HttpServletRequest request,@RequestBody Employee em){ String password= DigestUtils.md5DigestAsHex(em.getPassword().getBytes()); String username=em.getUsername(); LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>(); queryWrapper.eq(Employee::getUsername,username); Employee employee=employeeService.getOne(queryWrapper); if (employee==null){ return R.error("用户不存在"); } if (!password.equals(employee.getPassword())){ return R.error("密码错误"); } request.getSession().setAttribute("employee",employee.getId()); return R.success(employee); } }
解决方法:
第一种: 返回的类R中添加getter,setter方法
public class R <T>{ public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } private Integer code; private String msg; private T data; public static<T> R<T> success(T o){ R<T> r=new R<T>(); r.code=1; r.msg=""; r.data=o; return r; } public static<T> R<T> error(String str){ R r=new R(); r.code=0; r.msg=str; return r; } }
第二种方法:
使用@Data注解,这样自动装配了getter,setter方法
@Data public class R <T>{ private Integer code; private String msg; private T data; public static<T> R<T> success(T o){ R<T> r=new R<T>(); r.code=1; r.msg=""; r.data=o; return r; } public static<T> R<T> error(String str){ R r=new R(); r.code=0; r.msg=str; return r; } }