JAVAWEB应用模块(一)登录模块
java后台代码(MD5加密+token验证):
import com.smart.ssai.admin.domain.User; import com.smart.ssai.admin.service.UserService; import com.smart.ssai.VO.Response; import com.smart.ssai.common.utils.ResultVOUtil; import com.smart.ssai.common.utils.ToolUtils; import com.smart.ssai.constant.TokenConstant; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Date; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/api") public class LoginController { @Autowired private UserService userService; /** * 用户登录 * @param username 用户名 * @param password 密码 * @return */ @PostMapping("/login") public ResponseEntity<Response> login(@RequestParam(value = "username") String username , @RequestParam(value = "password") String password){ User user = userService.getUserByUsername(username); //判断用户是否存在 if(null == user){ return ResultVOUtil.show(0,"用户不存在,请重新输入",null); } //判断密码是否正确 String password1 = ToolUtils.md5Hex(password,String.valueOf(user.getCode())); if(!user.getPassword().equals(password1)){ return ResultVOUtil.show(0,"用户密码错误",null); } //登录成功,生成token,并更新数据库token和过期时间 Date date = new Date(); Integer nowTime = (int)(date.getTime()/1000);//当前时间戳 String token = createToken(user,date);//token User model = new User(); BeanUtils.copyProperties(user,model); // model.setId(user.getId()); model.setTimeout(nowTime); model.setToken(token); userService.insert(model); //跳转到指定页面,这里不跳转,返回token信息给前端 Map<String,Object> map = new HashMap<>(); map.put("token",token); return ResultVOUtil.show(1,"登录成功",map); } /** * 生成token,根据有效的用户信息 * @param user 用户实例 * @param date 当前日期 * @return */ private String createToken(User user, Date date){ SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")//设置header .setHeaderParam("alg", "HS256").setIssuedAt(date)//设置签发时间 .setExpiration(new Date(date.getTime() + TokenConstant.EXPIRE))//设置过期时间,30天,超出int,要加L .claim("userid",String.valueOf(user.getId()))//设置内容 .setIssuer(TokenConstant.ISSUER)//设置签发人 .signWith(signatureAlgorithm, TokenConstant.SECRETKEY);//签名,需要算法和key String jwt = builder.compact(); return jwt; } }