1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| package com.xlh.controller;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.xlh.common.api.CommonResult; import com.xlh.pojo.User; import com.xlh.service.LoginService; import com.xlh.util.JWTUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; @RestController @RequestMapping("/user") @CrossOrigin public class LoginController { @Autowired private LoginService loginService;
@RequestMapping(method = RequestMethod.POST, path="/login") @ResponseBody public CommonResult login(@RequestBody String requestBody) throws Exception{ JSONObject jsonObject = JSON.parseObject(requestBody); String name=jsonObject.getString("username"); String password=jsonObject.getString("password"); User user=loginService.getUser(name); System.out.println(user); if(user==null){ return CommonResult.success(200,"登录失败"); } else{ if(user.getPassword().equals(password)){ HashMap<String, String> map=new HashMap<>(); String token= JWTUtil.createToken(user); map.put("token",token); return CommonResult.success(200,"登录成功",map); } else{ return CommonResult.success(200,"登录失败"); } } }
@RequestMapping(method = RequestMethod.GET,value = "/info") @ResponseBody public CommonResult info(HttpServletRequest request) { String token = request.getHeader("Authorization"); HashMap<String, String> responseData = new HashMap<>(); responseData.put("roles","admin"); String username=JWTUtil.getUsername(token); responseData.put("username",username); responseData.put("avatar",""); return CommonResult.success(200,"获取成功",responseData); }
@RequestMapping(method = RequestMethod.POST,value = "/logout") @ResponseBody public CommonResult logout() { return CommonResult.success("ok"); } }
|