@PostMapping("/register")@ResponseBodypublicObjectregister(String username,String password){try{User user =newUser();user.setUsername(username);user.setPassword(password);userMapper.insert(user);return user;}catch(org.springframework.dao.DuplicateKeyException e){User user =newUser();return user;}}
3. 从服务器获取当前登录的信息
前端GET请求
后端
1. 判断用户是否Session中
2. 查询数据库 返回对应类
如果没有在则返回一个新的user
@GetMapping("/userInfo")@ResponseBodypublicObjectgetUserInfo(HttpServletRequest req){try{HttpSession httpSession = req.getSession(false);User user =(User) httpSession.getAttribute("user");// 拿着这个 user 对象, 去数据库中找, 找到最新的数据User newUser = userMapper.selectByName(user.getUsername());return newUser;}catch(NullPointerException e){returnnewUser();}}
4. UserAPI
packagecom.example.java_gobang.api;importcom.example.java_gobang.model.User;importcom.example.java_gobang.model.UserMapper;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.ResponseBody;importorg.springframework.web.bind.annotation.RestController;importjavax.annotation.Resource;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpSession;@RestControllerpublicclassUserAPI{@ResourceprivateUserMapper userMapper;@PostMapping("/login")@ResponseBodypublicObjectlogin(String username,String password,HttpServletRequest req){// 关键操作, 就是根据 username 去数据库中进行查询.// 如果能找到匹配的用户, 并且密码也一致, 就认为登录成功User user = userMapper.selectByName(username);System.out.println("[login] username="+ username);if(user ==null||!user.getPassword().equals(password)){// 登录失败System.out.println("登录失败!");returnnewUser();}HttpSession httpSession = req.getSession(true);httpSession.setAttribute("user", user);return user;}@PostMapping("/register")@ResponseBodypublicObjectregister(String username,String password){try{User user =newUser();user.setUsername(username);user.setPassword(password);userMapper.insert(user);return user;}catch(org.springframework.dao.DuplicateKeyException e){User user =newUser();return user;}}@GetMapping("/userInfo")@ResponseBodypublicObjectgetUserInfo(HttpServletRequest req){try{HttpSession httpSession = req.getSession(false);User user =(User) httpSession.getAttribute("user");// 拿着这个 user 对象, 去数据库中找, 找到最新的数据User newUser = userMapper.selectByName(user.getUsername());return newUser;}catch(NullPointerException e){returnnewUser();}}}