SpringBoot 封装返回类以及session 添加获取
程序员文章站
2022-04-24 16:56:22
1、创建返回类Result 2、创建 ResultUtil 返回对象 3、调用返回类 到此步 完成简单的返回类封装 4、session 的实现 ......
1、创建返回类Result
public class Result<T>{ /*错误码*/ private Integer code; /*提示信息 */ private String msg; /*具体内容*/ private T data; 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; } }
2、创建 ResultUtil 返回对象
public class ResultUtil { /** * 请求成功返回 * @param object * @return */ public static Result success(Object object){ Result Result=new Result(); Result.setCode(200); Result.setMsg("请求成功"); Result.setData(object); return Result; } public static Result success(){ return success(null); } public static Result error(Integer code,String resultResult){ Result Result=new Result(); Result.setCode(code); Result.setMsg(resultResult); return Result; } }
3、调用返回类
@RequestMapping("/link") @RestController public class LinkController { @Autowired private LinkRepository linkRepository; @PostMapping(value = "/list") @ResponseBody public Result getlinklList() { return ResultUtil.success(linkRepository.findAll()); } }
到此步 完成简单的返回类封装
4、session 的实现
public String hel(HttpSession request,Model model) { request.setAttribute("name","lisi"); //设置session值 String name = (String) request.getAttribute("name"); //获取session值 model.addAttribute("name",name); return "index"; }