登陆
怎么判断登陆的人是谁?
登陆成功了 就要发给他一个token/ticket
知识点:
1.UUID 中间有”-“ 可以用replaceAll(”-“,”“)替换掉,那么UUID出来的就是字符串了
UUID.randomUUID().toString().replaceAll(”-“,”“)
2测试用例:Assert.assertEquals
import com.nowcoder.dao.LoginTicketDAO;
import com.nowcoder.dao.NewsDAO;
import com.nowcoder.dao.UserDAO;
import com.nowcoder.model.LoginTicket;
import com.nowcoder.model.News;
import com.nowcoder.model.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.Date;
import java.util.Random;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ToutiaoApplication.class)
@Sql("/init-schema.sql")
public class InitDatabaseTests {
@Autowired
UserDAO userDAO;
@Autowired
NewsDAO newsDAO;
@Autowired
LoginTicketDAO loginTicketDAO;
@Test
public void initData() {
Random random = new Random();
for (int i = 0; i < 11; ++i) {
LoginTicket ticket = new LoginTicket();
ticket.setStatus(0);
ticket.setUserId(i+1);
ticket.setExpired(date);
ticket.setTicket(String.format("TICKET%d", i+1));
loginTicketDAO.addTicket(ticket);
loginTicketDAO.updateStatus(ticket.getTicket(), 2);
}
//单元测试 验证 第一个ticket1 的id是否为 1
// 验证 ticket1 的status 是否被更新为了2
Assert.assertEquals(1, loginTicketDAO.selectByTicket("TICKET1").getUserId());
Assert.assertEquals(2, loginTicketDAO.selectByTicket("TICKET1").getStatus());
}
思路:
1.需要ticket 就先设计一个ticket表
DROP TABLE IF EXISTS `login_ticket`;
CREATE TABLE `login_ticket` (
`id` INT NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
`ticket` VARCHAR(45) NOT NULL,
`expired` DATETIME NOT NULL,
`status` INT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE INDEX `ticket_UNIQUE` (`ticket` ASC));
2.在UserService中 生成ticket
private String addLoginTicket(int userId){
LoginTicket ticket = new LoginTicket();
ticket.setUserId(userId);
Date date = new Date();
date.setTime(date.getTime()+1000*3600*24);
ticket.setExpired(date);
ticket.setStatus(0);
ticket.setTicket(UUID.randomUUID().toString().replaceAll("-",""));
}
3.在UserService的login中判断是否是以及注册好的user
如果是就给他一个ticket,注意这次map是戴着T走向Controller的
public Map<String,Object> login(String username, String password){
Map<String,Object> map = new HashMap<>();
if (StringUtils.isBlank(username)) {
map.put("msgname", "用户名不能为空");
return map;
}
if (StringUtils.isBlank(password)) {
map.put("msgpwd", "密码不能为空");
return map;
}
User user = userDAO.selectByName(username);
if (user == null) {
map.put("msgname", "用户名不存在");
return map;
}
if(!ToutiaoUtil.MD5(password+user.getSalt()).equals(user.getPassword())){
map.put("msgpwd", "密码不正确");
return map;
}
//ticket 返回 userTicket
String ticket = addLoginTicket(user.getId());
map.put("ticket",ticket);
return map;
}
4.LoginController
因为map如果是注册成功登陆的是戴着Ticket 的
所以判断条件得改成 判断 map是否有ticket
同时得把ticket放到Cookie上 这样后端才能判断是否是一个人
//登陆
@RequestMapping(path = {"/login/"}, method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String reg(Model modelm, @RequestParam("username")String username,
@RequestParam("password")String password,
@RequestParam(value="rember",defaultValue = "0")int rember,
HttpServletResponse response) {
try{
//ticket Cookie
Map<String,Object> map =userService.register(username,password);
if(map.containsKey("ticket")){
Cookie cookie = new Cookie("ticket",map.get("ticket").toString());
cookie.setPath("/");
//如果记住 当前用户
if(rember >0){
cookie.setMaxAge(3600*24*5);
}
response.addCookie(cookie);
return ToutiaoUtil.getJSONString(0,"登陆成功");
}else{
return ToutiaoUtil.getJSONString(1,map);
}
}catch (Exception e){
logger.error("登陆异常:"+e.getMessage());
return ToutiaoUtil.getJSONString(1,"登陆异常");
}
}
代码:
1.Controller
2.userService
2.1//login
public Map<String,Object> login(String username, String password){
Map<String,Object> map = new HashMap<>();
if (StringUtils.isBlank(username)) {
map.put("msgname", "用户名不能为空");
return map;
}
if (StringUtils.isBlank(password)) {
map.put("msgpwd", "密码不能为空");
return map;
}
User user = userDAO.selectByName(username);
if (user == null) {
map.put("msgname", "用户名不存在");
return map;
}
if(!ToutiaoUtil.MD5(password+user.getSalt()).equals(user.getPassword())){
map.put("msgpwd", "密码不正确");
return map;
}
2.2 生成 ticket
private String addLoginTicket(int userId) {
LoginTicket ticket = new LoginTicket();
ticket.setUserId(userId);
Date date = new Date();
date.setTime(date.getTime() + 1000*3600*24);
ticket.setExpired(date);
ticket.setStatus(0);
ticket.setTicket(UUID.randomUUID().toString().replaceAll("-", ""));
loginTicketDAO.addTicket(ticket);
return ticket.getTicket();
}